Workshop › Pong › Step 22 of 26

Aim with the paddle

What we are doing

Right now the ball always bounces at the same angle. In real Pong, where the ball hits the paddle decides where it goes: near the top edge it flies up, near the bottom it flies down, in the middle straight.

```js
function bounceOff(paddle) {
  // -1 at the paddle's top edge, 0 in the middle, 1 at the bottom edge
  const offset = (ball.y + BALL / 2 - (paddle.y + PADDLE_H / 2)) / (PADDLE_H / 2)
  const speed = Math.abs(ball.vx)
  ball.vy = offset * 5
  if (paddle === left) {
    ball.vx = speed
    ball.x = left.x + PADDLE_W
  } else {
    ball.vx = -speed
    ball.x = right.x - BALL
  }
}

  if (ball.vx < 0 && touches(left)) bounceOff(left)
  if (ball.vx > 0 && touches(right)) bounceOff(right)
```

What it means

Your turn

  1. Under touches, write bounceOff.
  2. In update, replace the two paddle blocks with the two one-line calls.

Skills: Velocity and gravity, Functions

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