SCRATCH GOLD II
SCRATCH GOLD I
2 of 3

2.04 Gravity and jumping

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?

screenshot

To fix this, add gravity to your game. To do this, create a new variable called gravity.

  • Click on Variables in the Code tab, then click on Make a Variable.Variable blocks
  • Type in the name of your variable. You can choose whether you would like your variable to be available to all sprites, or to only this sprite. Press OK.Create variable
  • Once you have created the variable, it will be displayed on the Stage, or you can untick the variable in the Scripts tab to hide it.Variable on the stage

You can hide this variable from your Stage if you want to.

screenshot

Add these new code blocks that set gravity to a negative number and use the value of gravity to repeatedly change your character’s y-coordinate:

pico walking sprite

Click the flag, and then drag your character to the top of the Stage. What happens? Does the gravity work as you expect?

screenshot

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:

pico walking sprite

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?

screenshot

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:

pico walking sprite

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:

pico walking sprite

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 jump height variable that is set before the repeat starts. Then test your game.

Repeat these two steps until you’re happy with how high the character jumps.

×
×

Cart