Lesson 5 of 10

Gravity and jumping

Goal

Falling that speeds up and jumping only from the ground

01

Explanation

Gravity doesn't move an object directly. It changes the object's velocity: on every frame vy grows by GRAVITY * dt, then y moves by vy * dt. So a fall starts slow and then speeds up, just like in real life.

GRAVITY is measured in pixels per second squared, which is why you need dt in both steps. Forget it, and your game runs more than twice as fast on a 144 Hz screen as on a 60 Hz one.

Deal with the ground after the move. If the bottom of the object goes past floorY, put it back exactly on top of the floor and set vy to zero. If you only stopped the movement, the object would sink into the floor by the size of its last step. The same condition gives you the value of onGround. Allow jumping only from the ground, or the player could climb into the air just by pressing the key again and again.

02

Your task

Write update(p, dt, floorY) for an object shaped like { y, h, vy, onGround }. It applies gravity, then movement, then checks the ground, and it sets onGround on every call. Then write jump(p) to set vy to -JUMP_SPEED if the object is on the ground and do nothing otherwise. To try it, click the preview and press the space bar.

Checks

6 checks
  1. Gravity increases vy by GRAVITY × dt
  2. The position moves by vy × dt
  3. The object lands on the ground without sinking into it
  4. onGround is true only when touching the ground
  5. Jumping works only from the ground
  6. A jump actually lifts the object off the ground
03

Hints

0/3
Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.