Workshop › Pong › Step 22 of 26
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)
```offset compares the ball's middle with the paddle's middle and divides by half the paddle height: -1 at the top
edge, 0 in the middle, 1 at the bottom.ball.vy = offset * 5 sends it up or down that much.Math.abs gives the speed without its sign; the left paddle sends the ball right (+), the right one left (-).touches, write bounceOff.update, replace the two paddle blocks with the two one-line calls.Skills: Velocity and gravity, Functions
← Play again Faster every hit →