Lesson 34: Gravity
Many games use a physics engine to make elements interact with each other in a natural way. While creating an entire physics engine is beyond the scope of this series of videos, in this lesson you will add gravity to the mouse game.
1. Add a constant value for GRAVITY. This will be used to determine how far the mouse will be pushed down the page each time through the gameloop.
2. In initializeGame(), note that the top value of the mouse is initially set to 250px, to place the mouse on the ground. Change this value to 0px so that the mouse will start high up in the air. In this way we can apply gravity to make the mouse fall to the ground.
3. In the gameloop(), add code to increase the top value of mouse by GRAVITY only if it is still in the air (it has a top value less than 250px).
Now the mouse should fall from the top of the gameWindow until it hits the ground.
However, this does not look realistic. In reality, objects falling gain speed as they fall.
4. Create a variable to keep track of the vertical speed of the mouse and set it to 0.
5. Modify the code in gameloop() so that mouseFallSpeed increases every time through the gameloop(), and the top value of the mouse is increased by this changing value of mouseFallSpeed.
When you refresh the page you should see the mouse fall from the sky more realistically, starting slow and gaining speed on the way down.
One remaining problem is that the mouse does ends up lower than the desired position. This is because the top value of the mouse is increased by mouseFallSpeed (which is large when the mouse gets to the bottom) from being less than 250px to being more than 250px without actually hitting 250px.
6. Modify the code to ensure that the top value of the mouse is never greater than 250px.
This is a simple example of using gravity to make something fall. The code will be a bit more complex if their are multiple platforms at different heights that the mouse can land on. In that case, you would have to include a hittest for each object to determine if the mouse should stop falling. This will come in a later set of lessons.