Lesson 5 of 10
Gravity and jumping
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Falling that speeds up and jumping only from the ground
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.
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- Gravity increases vy by GRAVITY × dt
- The position moves by vy × dt
- The object lands on the ground without sinking into it
- onGround is true only when touching the ground
- Jumping works only from the ground
- A jump actually lifts the object off the ground