Code the Collisions
With a collider made, we now need to tell the drone to stop moving when it bumps into a boulder.
This tutorial will show you how to code the player to interact with a collider and stop moving.
It works by asking the drone to check: ‘if i move, will i be hitting a collider?’.
- If the drone would be hitting the boulder, then the drone can’t move.
- If the drone would not be hitting the boulder, then the drone can move.
Example Code
The following code is an updated version of the drones ‘step’ movement code.
Instead of moving the character without checking to see if it would hit anything, this new code first checks to see if the drone would hit anything if it moves. If it wouldn’t hit the object, the movement is carried out.
- If moving doesn’t hit the BoulderObject, then the drone can move in that direction.
- If moving does hit the BoulderObject, then the drone can not move in that direction.
//Sets the movement speed of the Drone to 6
var move_speed = 6;
//Sets two "placeholder" variables to 0, one for X value, one for Y value.
var mx = 0;
var my = 0;
//If the W key is pressed, change the placeholder Y value by movespeed to check moving up.
if (keyboard_check(ord("W"))) my -= move_speed;
//If the S key is pressed, change the placeholder Y value by movespeed to check moving down.
if (keyboard_check(ord("S"))) my += move_speed;
//If the A key is pressed, change the placeholder X value by movespeed to check moving left.
if (keyboard_check(ord("A"))) mx -= move_speed;
//If the D key is pressed, change the placeholder X value by movespeed to check moving right.
if (keyboard_check(ord("D"))) mx += move_speed;
//Checks to see if the player can move left or right without hitting a BoulderObject
//Checks to see if moving left or right by the placeholder X value does not
//result in hitting the BoulderObject.
if (!place_meeting(x + mx, y, BoulderObject))
{
//if the new position won't hit a BoulderObject, then we update the X position by mx.
x += mx;
}
//Checks to see if the player can move up and down without hitting a BoulderObject
//Checks to see if moving left or right by the placeholder X value does not
//result in hitting the BoulderObject.
if (!place_meeting(x, y + my, BoulderObject))
{
//if the new position won't hit a BoulderObject, then we update the Y position by mx.
y += my;
}