Platformer movement code

Here is some GML code for “pixel perfect” movement in a platform game.

 
This goes in the player object’s Create event:

//Initialize Variables
grav = 0.5;
hsp = 0;
vsp = 0;
jumpspeed = 10;
movespeed = 6;

 

This goes in the player object’s Step event:

//Get the player's input
 key_right = keyboard_check(vk_right);
 key_left = -keyboard_check(vk_left);
 key_jump = keyboard_check_pressed(vk_space);

//React to inputs and gravity
 move = key_left + key_right;
 hsp = move * movespeed;
 if (vsp < 10) vsp += grav;

// On the floor
if (place_meeting(x,y+1,obj_wall))
{
 vsp = key_jump * -jumpspeed;
}

// Horizontal collision
if (place_meeting(x+hsp,y,obj_wall))
{
  while (!place_meeting(x+sign(hsp),y,obj_wall))
  {
    x+= sign(hsp);
  }
  hsp = 0;
}
x += hsp;

// Vertical collision
if (place_meeting(x,y+vsp,obj_wall))
{
  while (!place_meeting(x,y+sign(vsp),obj_wall))
  {
    y+= sign(vsp);
  }
  vsp = 0;
}
y += vsp;

 

This is taken from https://www.youtube.com/watch?v=izNXbMdu348

 

 

Leave a Reply