Workshop › Pong › Step 16 of 26
When the ball gets past a paddle it is gone for good. Now a serve function puts a new ball in the middle and sends it
toward the player who missed.
```js
let ball
function serve(direction) {
ball = {
x: canvas.width / 2 - BALL / 2,
y: canvas.height / 2 - BALL / 2,
vx: 4 * direction,
vy: Math.random() < 0.5 ? -3 : 3,
}
}
if (ball.x + BALL < 0) serve(-1)
else if (ball.x > canvas.width) serve(1)
serve(1)
```serve(direction) makes a new ball object in the middle. direction is 1 (to the right) or -1 (to the left).Math.random() < 0.5 ? -3 : 3 goes up or down, each half of the time.ball.x + BALL < 0) means the left player missed: serve to the left (-1).serve(1) at the bottom makes the first ball.let ball = { ... } to just let ball.clamp, write serve.update, after an empty line, write the two out-of-bounds lines.serve(1) right above requestAnimationFrame(loop) at the bottom.Skills: Game states, Functions
← The paddles hit back Keep the score →