Save-Point
[GML] 8-Directional Movement code - Printable Version

+- Save-Point (https://www.save-point.org)
+-- Forum: Archives (https://www.save-point.org/forum-105.html)
+--- Forum: Creation Asylum Archives (https://www.save-point.org/forum-90.html)
+---- Forum: Scripts & Code Snippets (https://www.save-point.org/forum-92.html)
+----- Forum: Game Maker Code (https://www.save-point.org/forum-106.html)
+----- Thread: [GML] 8-Directional Movement code (/thread-6974.html)



[GML] 8-Directional Movement code - InFecTioN - 05-26-2011

This is a locked, single-post thread from Creation Asylum. Archived here to prevent its loss.
No support is given. If you are the owner of the thread, please contact administration.


This bit of code will allow your object to move in 8 directions.

Create Event

Code:
normal_speed = 5
is_move_vert = false
is_move_hori = false
move_speed   = normal_speed



Step Event

Code:
//Check and control player movement

is_move_vert = false
is_move_hori = false
dx = 0
dy = 0
divider = 1.0;

//Check differences in x and y coordinate according to key pressed.
//Check differences in x and y coordinate according to key pressed.

if (keyboard_check(vk_up))

{
dy = -move_speed;
}

if (keyboard_check(vk_down))

{
dy = move_speed;
}

if (keyboard_check(vk_left))

{
dx= -move_speed;
}

if (keyboard_check(vk_right))

{
dx = move_speed;
}

//Check movement orientation

if (keyboard_check(vk_up) or keyboard_check(vk_down))

{
is_move_vert = true;
}

if (keyboard_check(vk_left) or keyboard_check(vk_right))

{
is_move_hori = true;
}

//If move diagonally, then we need to divide the distance in x and y by square root of 2.

if( is_move_vert == true and is_move_hori == true )

{
divider = sqrt(2);
}

x+=dx/divider

y+=dy/divider