Skip to content

Gravity and Vertical Collisions

  • Lesson
  • 2 min read
  • 7 of 9 in this chapter

Variables

Go back to our player object, and click on "Add Event" and make the event "Create" . Now add this code:

Text
vspd = 0;
grav = 0.2;

When setting a variable for your gravity make sure to NOT use "gravity". Gravity is an inbuilt variable. Make sure to note that adding positive values to the y-axis makes you go down.

Implementing it

Now we are going to create another event for our player object which is a "step" event. Step events basically execute their code per second depending on the room_speed value. Now add this code to it:

Text
if (vspd < 20) vspd += grav;

if (place_meeting(x, y + vspd , obj_wall)) 
{
 vspd = 0;
}
y = y + vspd

Basically what this code is doing is adding the value of "grav" on vspd when the value of it is below 20, and the last line of code is updating the y value of our character. The code on line 2 is checking if there is a wall object below within 1px. If there is, the value of "vspd" will become 0, so no more updates will be made to the y value by gravity and stay vspd amount of px on top of the wall object.