Lesson 1 of 10
The game loop
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
Call update, then draw, about sixty times a second
Explanation
Every game, from Pong to the biggest titles, runs on a single loop that repeats over and over: it updates the game state, then draws it. requestAnimationFrame calls your loop before each frame the browser paints, which is about sixty times a second.
What keeps movement at the same speed on every device is multiplying it by dt, the time that has passed since the previous frame. Skip that, and your game runs faster on fast screens and slower on slow ones.
Keep update separate from draw. The update function only works out the game logic and has nothing to do with drawing, so you can test it on its own and reuse it. The draw function reads the state and draws it without changing anything.
Your task
Write update(ball, dt, width) so it moves the ball by vx * dt. If the ball goes past the right or left wall, flip the sign of vx so it bounces back. The drawing and the loop are already done.
Checks
5 checks- update is defined
- Movement is proportional to dt
- The ball bounces off the right wall
- The ball bounces off the left wall
- The ball doesn't move when dt is zero