Lesson 4 of 10
A Pong paddle
- 16 min
- 6 checks
- 3 hints
- Go to task
Goal
A paddle that stays on the court and a bounce the player controls
Explanation
Pong comes down to two things. The first is that the paddle never leaves the court: you move it by dir * speed * dt, then clamp its position between 0 and height - h. Clamp after the move, not before, because checking before the move lets the paddle overshoot the edge by a whole frame's worth of movement.
The second is what makes it a game of skill. The ball doesn't bounce the way light reflects off a mirror. Its angle depends on where it hits the paddle: a hit in the middle sends it straight back, and the closer the hit is to either end, the steeper the angle, up to 60°. That's how the player aims the ball with the paddle.
To work this out, offset runs from -1 at the top end to 1 at the bottom end, and the angle is offset * Math.PI / 3. Then you split the same speed between the two axes using cos and sin, so the angle changes the ball's direction but not how fast it's going.
Your task
Write movePaddle(paddle, dir, dt, height), where dir is -1, 0 or 1, and keep the paddle { x, y, w, h, speed } inside the court. Then write bounce(ball, paddle) for the left paddle so it keeps the speed Math.hypot(vx, vy) unchanged, makes vx positive, and works out vy from where the ball hit. The paddle in the preview plays by itself.
Checks
6 checks- The paddle moves by dir × speed × dt
- The paddle can't leave the court at the top or the bottom
- A hit in the middle sends the ball straight back
- The top of the paddle sends the ball up and the bottom sends it down
- A hit farther from the middle gives a steeper angle
- The ball bounces back at the same speed