Workshop › Pong › Step 13 of 26

Bounce off the top and bottom

What we are doing

When the ball leaves the court at the top or bottom, it bounces: the vertical speed flips sign, and the ball is put back inside so it cannot get stuck in the wall.

```js
if (ball.y < 0 || ball.y + BALL > canvas.height) {
  ball.vy = -ball.vy
  ball.y = clamp(ball.y, 0, canvas.height - BALL)
}
```

What it means

Your turn

At the end of update, under the two ball lines, write the if block.

Skills: Velocity and gravity, Collision detection

All steps

  1. Get the canvas and the pen
  2. A black court
  3. One dash of the net
  4. The whole net
  5. Two paddles
  6. A function that draws
  7. The game loop
  8. Remember held keys
  9. Move the paddles
  10. Stay on the court
  11. The ball
  12. The ball moves
  13. Bounce off the top and bottom
  14. Does the ball touch a paddle?
  15. The paddles hit back
  16. Serve again
  17. Keep the score
  18. Show the score
  19. First to five
  20. Who won?
  21. Play again
  22. Aim with the paddle
  23. Faster every hit
  24. A computer opponent
  25. One player or two
  26. Build it yourself: a serve pause