TExcelTAD
Home › 2D Games with JavaScript & Canvas › Pong 2: Bounces & Collisions

Pong 2: Bounces & Collisions

In Pong 1 the ball ignored the paddles. Now we make them solid. A good Pong bounce does more than reverse direction: where the ball hits the paddle decides the angle it leaves at, and every hit makes the ball a little faster. That one rule is what turns Pong from a screensaver into a game of skill.

Step 1: did the ball touch the paddle?

The ball and the paddles are axis-aligned rectangles, so the test is the AABB overlap you met in Collision Detection: two boxes overlap when they overlap on both axes.

js
function hits(b, p) {
  return b.x < p.x + PADDLE_W && b.x + b.size > p.x &&
         b.y < p.y + PADDLE_H && b.y + b.size > p.y;
}

We only check the left paddle while the ball moves left (vx < 0) and the right paddle while it moves right. Without that guard, a ball that is still overlapping the paddle on the next step would bounce again and get trapped inside it.

Step 2: the bounce angle

Measure how far from the paddle's centre the ball hit, as a number from -1 (top edge) to +1 (bottom edge). Turn that into an angle up to ±60°, keep the speed, and send the ball back the other way:

Hit position offset Leaves at
top edge -1 60° upwards
centre 0 straight across
bottom edge +1 60° downwards

Here is the rule as a pure function, so you can see the numbers:

js · try it yourself
const MAX_ANGLE = Math.PI / 3;   // 60 degrees

function paddleBounce(ballCenterY, paddleCenterY, halfHeight, speed, dir) {
  const offset = Math.max(-1, Math.min(1, (ballCenterY - paddleCenterY) / halfHeight));
  const angle = offset * MAX_ANGLE;
  return { vx: dir * speed * Math.cos(angle), vy: speed * Math.sin(angle) };
}

for (const y of [100, 112.5, 125, 137.5, 150, 160]) {
  const { vx, vy } = paddleBounce(y, 125, 25, 300, 1);
  console.log(`ball at y=${y}: vx=${vx.toFixed(1)} vy=${vy.toFixed(1)}`);
}
ball at y=100: vx=150.0 vy=-259.8
ball at y=112.5: vx=259.8 vy=-150.0
ball at y=125: vx=300.0 vy=0.0
ball at y=137.5: vx=259.8 vy=150.0
ball at y=150: vx=150.0 vy=259.8
ball at y=160: vx=150.0 vy=259.8

Notice that the length of (vx, vy) is always 300: cos²+sin² = 1, so the angle changes the direction but not the speed. The last row is clamped: a ball that clips the very end of the paddle can't leave at a crazier angle than 60°.

Tip: Never allow a bounce angle near 90°. A ball moving almost straight up and down takes forever to cross the court and the rally becomes boring.

Step 3: speeding up

Each paddle hit multiplies the speed by 1.06, capped at MAX_SPEED. Rallies start calm and get tense. The cap also protects the collision test: at 520 px/s the ball moves about 8.7 px per update, less than ball + paddle width (16 px), so it can never jump over a paddle between two updates. That jump is called tunneling, and the faster your objects get, the more you have to think about it.

The playable step

Click and play both sides: W/S and ↑/↓. Try hitting the ball with a paddle edge:

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

// ---- Pong, step 2: paddle collisions with a bounce angle ----
const PADDLE_W = 8, PADDLE_H = 50, PADDLE_SPEED = 260;
const BALL_SPEED = 220, SPEEDUP = 1.06, MAX_SPEED = 520, MAX_ANGLE = Math.PI / 3;
const left = { x: 16, y: H / 2 - PADDLE_H / 2 };
const right = { x: W - 16 - PADDLE_W, y: H / 2 - PADDLE_H / 2 };
const ball = { x: 0, y: 0, size: 8, vx: 0, vy: 0 };

function resetBall(dir) {
  ball.x = W / 2 - ball.size / 2;
  ball.y = H / 2 - ball.size / 2;
  ball.vx = dir * BALL_SPEED * Math.cos(0.4);
  ball.vy = BALL_SPEED * Math.sin(0.4);
}
resetBall(1);

function movePaddle(p, up, down, dt) {
  if (keys.has(up)) p.y -= PADDLE_SPEED * dt;
  if (keys.has(down)) p.y += PADDLE_SPEED * dt;
  p.y = Math.max(0, Math.min(H - PADDLE_H, p.y));
}

function hits(b, p) {
  return b.x < p.x + PADDLE_W && b.x + b.size > p.x &&
         b.y < p.y + PADDLE_H && b.y + b.size > p.y;
}

function bounceOff(p, dir) {
  const offset = (ball.y + ball.size / 2 - (p.y + PADDLE_H / 2)) / (PADDLE_H / 2);
  const angle = Math.max(-1, Math.min(1, offset)) * MAX_ANGLE;
  const speed = Math.min(Math.hypot(ball.vx, ball.vy) * SPEEDUP, MAX_SPEED);
  ball.vx = dir * speed * Math.cos(angle);
  ball.vy = speed * Math.sin(angle);
}

function update(dt) {
  movePaddle(left, 'KeyW', 'KeyS', dt);
  movePaddle(right, 'ArrowUp', 'ArrowDown', dt);

  ball.x += ball.vx * dt;
  ball.y += ball.vy * dt;
  if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
  if (ball.y + ball.size > H) { ball.y = H - ball.size; ball.vy = -Math.abs(ball.vy); }

  if (ball.vx < 0 && hits(ball, left)) {
    ball.x = left.x + PADDLE_W;            // push out of the paddle first
    bounceOff(left, 1);
  }
  if (ball.vx > 0 && hits(ball, right)) {
    ball.x = right.x - ball.size;
    bounceOff(right, -1);
  }

  if (ball.x + ball.size < 0) resetBall(1);     // missed on the left
  if (ball.x > W) resetBall(-1);                // missed on the right
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#2a2f45';
  for (let y = 4; y < H; y += 16) ctx.fillRect(W / 2 - 1, y, 2, 8);
  ctx.fillStyle = '#e8eaf6';
  ctx.fillRect(Math.round(left.x), Math.round(left.y), PADDLE_W, PADDLE_H);
  ctx.fillRect(Math.round(right.x), Math.round(right.y), PADDLE_W, PADDLE_H);
  ctx.fillStyle = '#ffb74d';
  ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
  // Speed readout, so you can watch the speed-up.
  ctx.fillStyle = '#5c6380';
  ctx.font = '12px system-ui, sans-serif';
  ctx.textAlign = 'left';
  ctx.fillText(`speed ${Math.round(Math.hypot(ball.vx, ball.vy))} px/s`, 8, H - 8);
}

run(update, draw, 'W/S and ↑/↓ move the paddles');
</script>

Order matters: push out, then bounce

On a hit we first move the ball so it touches the paddle's face (ball.x = left.x + PADDLE_W) and only then change its velocity. Resolving the overlap before reacting to it is a pattern you'll see in every collision system, from Breakout bricks to platformer tiles.

Note: The ball hitting the top or bottom end of a paddle is a corner case (literally). Our simple version treats it like a face hit. Breakout, where corners matter more, uses a smarter rule based on overlap depth; see Breakout 2.

Test yourself

Why is the left paddle only checked while ball.vx < 0?

  1. To save time
  2. So a ball still overlapping the paddle after a bounce isn't bounced again and trapped
  3. Because the left paddle can't move
  4. It is required by AABB tests

With MAX_ANGLE = 60°, the ball hits exactly the paddle's centre. How does it leave?

  1. At 60° up
  2. Straight across (vy = 0)
  3. At 60° down
  4. It stops

What is tunneling?

  1. A ball moving so far in one update that it skips over a thin object
  2. A rendering bug with gradients
  3. Moving the ball under the paddle
  4. Using Math.abs on velocities