GML - Movement collisions script

From Global Programming Syntax

Jump to: navigation, search

In nearly every game you will need a system of collisions. Although most people will choose to use the collisions event it can be far easier to just use a small GML script in some cases. Below is an example:

Example Code

If you have a play and don't want the player to be able to move into any other object but instead want other objects to move onto the player, then the following script will allow that. All you need to do is first place the following code into the player step event.

{
var xx, xxx, yy, yyy, sprite, spritew, spriteh, movementspeed;
sprite='sprite1'; //set the sprite of the current object
movementspeed=4; //set the movement speed
 
spritew=sprite_get_width(sprite);
spriteh=sprite_get_height(sprite);
xx=x-(spritew/2)-movementspeed;
yy=y+(spriteh/2);
yyy=y-(spriteh/2);
if (keyboard_check(vk_left) && position_empty(xx,yy) && position_empty(xx,yyy)) { x -= movementspeed; }
xx=x+(spritew/2)+movementspeed;
yy=y+(spriteh/2);
yyy=y-(spriteh/2);
if (keyboard_check(vk_right) && position_empty(xx,yy) && position_empty(xx,yyy)) { x += movementspeed; }
xx=x+(spritew/2);
xxx=x-(spritew/2);
yy=y-(spriteh/2)-movementspeed;
if (keyboard_check(vk_up) && position_empty(xx,yy) && position_empty(xxx,yy)) { y -= movementspeed; }
xx=x+(spritew/2);
xx=x-(spritew/2);
yy=y+(spriteh/2)+movementspeed;
if (keyboard_check(vk_down) && position_empty(xx,yy) && position_empty(xxx,yy)) { y += movementspeed; }
 
}

Now you will need to configure the variables sprite to the name of the sprite associated with the object and the variable movementspeed needs to be changed to the speed the object will move. After changing those 2 variables, simply open the objects sprite through the side bar and center the origin of it. Centering the origin means to make the sprites grid centered. Then you should be able to use the keyboard arrows to movearound without going through any objects.

Personal tools
languages
page stats
Toolbox