SOLVED Smooth grid movement

Dane Emark

Member
Hi, I am totally new to the GameMaker forum:).
NOTE: I am still using GameMaker Studio 1.4 so I don't know if Game Maker studio 2 code can work.
I was making a test game to improve my programming skills.
I wanted the player, the enemies, and the other objects to move on a fixed grid(32x32);
here is the code of the obj_player :
//Create event
spd = 2
xprev = x
yprev = y
//Step Event
var lkey = keyboard_check_pressed(vk_left);
var rkey = keyboard_check_pressed(vk_right);
var ukey = keyboard_check_pressed(vk_up);
var dkey = keyboard_check_pressed(vk_down);
if (clicked = false && finish = true) {
if (lkey && !instance_place(x-32,y,obj_wall) && instance_place(x-32,y,obj_select_place)) {
direction = 180;
clicked = true;
finish = false;
}
if (rkey && !instance_place(x+32,y,obj_wall) && instance_place(x+32,y,obj_select_place)) {
direction = 0;
clicked = true;
finish = false;
}
if (ukey && !instance_place(x,y-32,obj_wall) && instance_place(x,y-32,obj_select_place)) {
direction = 90;
clicked = true;
finish = false;
}
if (dkey && !instance_place(x,y+32,obj_wall) && instance_place(x,y+32,obj_select_place)) {
direction = 270;
clicked = true;
finish = false;
}
}
if (clicked = true) {
if (direction = 0) {
x += spd;
if (xprev+32 = x) {
clicked = false;
}
} else if (direction = 90) {
y += -spd;
if (yprev-32 = y) {
clicked = false;
}
} else if (direction = 180) {
x += -spd;
if (xprev-32 = x) {
clicked = false;
}
} else if (direction = 270) {
y += spd;
if (yprev+32 = y) {
clicked = false;
}
}
}
if (clicked = false) {
xprev = x;
yprev = y;
}
Is there any other way? and can I optimize this code?
I'll really appreciate your reply.
 

Let's Clone

Member
If you're interested in some examples I teach how to clone classic games on my youtube channel and I use grids HEAVILY haha. I'm currently putting together a video on ds_grids themselves, going over use-cases and grid functionality. Hopefuly it will be up in a couple of days.
 

Let's Clone

Member
Instead of running an if-statement for every direction or input, you can use variables like h_spd/v_spd for you horizontal and vertical directions and populate those values with your input multiplied by your speed.
For example:

GML:
h_spd = (rkey - lkey) * spd;
v_spd = (dkey - ukey) * spd;

// Do whatever you need for collisions or grid-locking here

x += h_spd;
y += v_spd;
 
Top