Now you’re going to make your character move more realistically: you’re going to add gravity to your game and give the character the ability to jump.
In the game, move your character so that it walks off a platform. Do you see that it can walk into empty space?
To fix this, add gravity to your game. To do this, create a new variable called gravity
.
Add these new code blocks that set
to a negative number and use the value of gravity
to repeatedly change your character’s y-coordinate:gravity
Click the flag, and then drag your character to the top of the Stage. What happens? Does the gravity work as you expect?
Gravity shouldn’t move the character sprite through a platform or a ladder! Add an if
block to your code to only let the gravity work when the character is in mid-air. The gravity code should then look like this:
Test the game again to see whether gravity works correctly now. Does your character sprite stop falling when it touches a platform or a ladder? Can you make the character walk off the edge of platforms and fall onto the level below?
Now add code to make your character jump whenever the player presses the space key. One very easy way to do this is to move your character up a few times:
Because gravity is constantly pushing your character down by 4 pixels, you need to choose a number greater than 4
in your change y by (4)
block. Change the number until you’re happy with the height the character jumps.
Test out your code. Notice that the jumping movement isn’t very smooth. To make jumping look smoother, you need to move your character sprite by smaller and smaller amounts, until it is not rising any higher.
To do this, create a new variable called jump height
. Again, you can hide this variable if you prefer.
Delete the jumping code you added to your character sprite, and add this code instead:
This code moves your character up by 8 pixels, then 7.5 pixels, then 7 pixels, and so on, until it does not rise any higher. This makes jumping look much smoother.
Change the value of the
variable that is set before the jump height
repeat
starts. Then test your game.
Repeat these two steps until you’re happy with how high the character jumps.