To enable collisions in a moving object, you can do this:
- Set the movement speed (usually
hsp
andvsp
) - Check if there are collisions where you’re moving (separately on
x
andy
) - If a collision is found on either dimension, you set that dimension’s speed to 0
- Before setting it to 0, you run a
while
loop to close any gap between the two colliding instances
- Before setting it to 0, you run a
Using the simple place_meeting()
function, the code would look something like this:
/// Step event
// Set speed
hsp = input_x * move_speed;
vsp = input_y * move_speed;
// Check collisions: X
if (place_meeting(x + hsp, y, obj_wall)) {
// Close the gap with a while loop
while (!place_meeting(x + sign(hsp), y, obj_wall)) {
x += sign(hsp);
}
// Stop
hsp = 0;
}
// Check collisions: Y
if (place_meeting(x, y + vsp, obj_wall)) {
// Close the gap with a while loop
while (!place_meeting(x, y + sign(vsp), obj_wall)) {
y += sign(vsp);
}
// Stop
vsp = 0;
}
// Finally, apply movement
x += hsp;
y += vsp;