TExcelTAD
Home › 2D Games with JavaScript & Canvas › Breakout 2: Collision Response

Breakout 2: Collision Response

Detecting a collision answers "did they touch?". Collision response answers the harder question: "what happens now?". In Breakout 1 every brick hit flipped the vertical velocity, which looks wrong when the ball clips a brick's side. In this lesson we work out which side was hit, push the ball out along that axis, and bounce on that axis only. We also let the player aim with the paddle.

Which side did we hit? Overlap depth

When two boxes overlap, measure how deep the overlap is on each axis:

overlapX = min(ball.right - brick.left, brick.right - ball.left)
overlapY = min(ball.bottom - brick.top, brick.bottom - ball.top)

The axis with the smaller overlap is the one the ball came through. Think about it: a ball that has just come up from below into a brick overlaps it by a pixel or two vertically, but horizontally it may overlap by its full width. So:

Smaller overlap Ball came through Response
overlapY the top or bottom face push out vertically, flip vy
overlapX the left or right face push out horizontally, flip vx

Which way to push is decided by comparing centres: if the ball's centre is left of the brick's centre, push it left.

The resolver as a pure function

Here it is, tested on three situations: hitting a brick from below, from the left, and the case where the ball is moving away already.

js · try it yourself
function resolve(ball, r) {
  const overlapX = Math.min(ball.x + ball.size - r.x, r.x + r.w - ball.x);
  const overlapY = Math.min(ball.y + ball.size - r.y, r.y + r.h - ball.y);
  if (overlapX <= 0 || overlapY <= 0) return 'none';
  const ballCx = ball.x + ball.size / 2, ballCy = ball.y + ball.size / 2;
  if (overlapX < overlapY) {
    if (ballCx < r.x + r.w / 2) { ball.x -= overlapX; ball.vx = -Math.abs(ball.vx); }
    else { ball.x += overlapX; ball.vx = Math.abs(ball.vx); }
    return 'side';
  }
  if (ballCy < r.y + r.h / 2) { ball.y -= overlapY; ball.vy = -Math.abs(ball.vy); }
  else { ball.y += overlapY; ball.vy = Math.abs(ball.vy); }
  return 'top/bottom';
}

const brick = { x: 100, y: 50, w: 44, h: 12 };
const cases = {
  "from below": { x: 120, y: 60, size: 6, vx: 80, vy: -200 },
  "from the left": { x: 96, y: 53, size: 6, vx: 150, vy: -60 },
  "missed": { x: 150, y: 53, size: 6, vx: 150, vy: -60 },
};
for (const [name, ball] of Object.entries(cases)) {
  const hit = resolve(ball, brick);
  console.log(`${name.padEnd(13)} -> ${hit.padEnd(10)} ball now`, ball);
}
from below    -> top/bottom ball now { x: 120, y: 62, size: 6, vx: 80, vy: 200 }
from the left -> side       ball now { x: 94, y: 53, size: 6, vx: -150, vy: -60 }
missed        -> none       ball now { x: 150, y: 53, size: 6, vx: 150, vy: -60 }

Two details make this robust:

  • Push out by exactly the overlap. After resolving, the ball touches the brick's face but no longer overlaps it, so the next update can't detect the same hit again.
  • Set the sign, don't flip it. vx = -Math.abs(vx) means "move left", whatever the ball was doing. Just like Pong's walls, this can't get stuck.

Note: When overlapX and overlapY are nearly equal, the ball hit a corner. Our rule treats exact ties as top/bottom hits, which feels natural in Breakout because the bricks are wide. Physics engines handle corners more carefully, but for a brick game this is the classic, good-enough answer.

Aiming with the paddle

Breakout without aiming is luck. We reuse Pong's idea: the hit position on the paddle (-1 at the left end, +1 at the right end) chooses the angle, this time measured from straight up:

js
const offset = (ball.x + ball.size / 2 - (paddle.x + PADDLE_W / 2)) / (PADDLE_W / 2);
const angle = Math.max(-1, Math.min(1, offset)) * MAX_ANGLE;     // 0 = straight up
ball.vx = speed * Math.sin(angle);
ball.vy = -speed * Math.cos(angle);

Hitting with the left end sends the ball up and left; the centre sends it straight up.

Step 2: playable

Same controls: ←/→ or A/D, Space to launch. Try clipping the sides of bricks and aiming for the gaps:

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 ----

// ---- Breakout, step 2: side-aware brick collisions and paddle aiming ----
const PADDLE_W = 64, PADDLE_H = 8, PADDLE_SPEED = 320, BALL_SPEED = 230, MAX_ANGLE = Math.PI / 3;
const COLS = 10, ROWS = 5, BRICK_W = 44, BRICK_H = 12, GAP = 2;
const LEFT = (W - (COLS * (BRICK_W + GAP) - GAP)) / 2;
const ROW_COLORS = ['#ef5350', '#ffa726', '#ffee58', '#66bb6a', '#42a5f5'];
const paddle = { x: W / 2 - PADDLE_W / 2, y: H - 20 };
const ball = { x: 0, y: 0, size: 6, vx: 0, vy: 0, stuck: true };
const bricks = [];
for (let row = 0; row < ROWS; row++) {
  for (let col = 0; col < COLS; col++) {
    bricks.push({ x: LEFT + col * (BRICK_W + GAP), y: 30 + row * (BRICK_H + GAP), w: BRICK_W, h: BRICK_H, row });
  }
}

// Push the ball out along the axis of least overlap and bounce on that axis.
function resolve(r) {
  const overlapX = Math.min(ball.x + ball.size - r.x, r.x + r.w - ball.x);
  const overlapY = Math.min(ball.y + ball.size - r.y, r.y + r.h - ball.y);
  if (overlapX <= 0 || overlapY <= 0) return false;
  if (overlapX < overlapY) {
    if (ball.x + ball.size / 2 < r.x + r.w / 2) { ball.x -= overlapX; ball.vx = -Math.abs(ball.vx); }
    else { ball.x += overlapX; ball.vx = Math.abs(ball.vx); }
  } else {
    if (ball.y + ball.size / 2 < r.y + r.h / 2) { ball.y -= overlapY; ball.vy = -Math.abs(ball.vy); }
    else { ball.y += overlapY; ball.vy = Math.abs(ball.vy); }
  }
  return true;
}

function launch(angle) {
  ball.vx = BALL_SPEED * Math.sin(angle);
  ball.vy = -BALL_SPEED * Math.cos(angle);
}

function update(dt) {
  if (keys.has('ArrowLeft') || keys.has('KeyA')) paddle.x -= PADDLE_SPEED * dt;
  if (keys.has('ArrowRight') || keys.has('KeyD')) paddle.x += PADDLE_SPEED * dt;
  paddle.x = Math.max(0, Math.min(W - PADDLE_W, paddle.x));

  if (ball.stuck) {
    ball.x = paddle.x + PADDLE_W / 2 - ball.size / 2;
    ball.y = paddle.y - ball.size;
    if (pressed.has('Space')) { ball.stuck = false; launch(0.35); }
    return;
  }

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

  // Paddle: the hit position chooses the angle (0 = straight up).
  if (ball.vy > 0 && ball.y + ball.size > paddle.y && ball.y < paddle.y + PADDLE_H &&
      ball.x + ball.size > paddle.x && ball.x < paddle.x + PADDLE_W) {
    ball.y = paddle.y - ball.size;
    const offset = (ball.x + ball.size / 2 - (paddle.x + PADDLE_W / 2)) / (PADDLE_W / 2);
    launch(Math.max(-1, Math.min(1, offset)) * MAX_ANGLE);
  }

  // Bricks: resolve the first hit only.
  const i = bricks.findIndex((b) => resolve(b));
  if (i !== -1) bricks.splice(i, 1);

  if (ball.y > H) ball.stuck = true;
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  for (const b of bricks) {
    ctx.fillStyle = ROW_COLORS[b.row];
    ctx.fillRect(Math.round(b.x), Math.round(b.y), b.w, b.h);
  }
  ctx.fillStyle = '#e8eaf6';
  ctx.fillRect(Math.round(paddle.x), Math.round(paddle.y), PADDLE_W, PADDLE_H);
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
  if (ball.stuck) {
    ctx.fillStyle = '#5c6380';
    ctx.font = '12px system-ui, sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('Space to launch', W / 2, H - 40);
  }
  if (bricks.length === 0) banner('Wall cleared!', 'Breakout 3 adds more levels');
}

run(update, draw, '←/→ or A/D to move · Space to launch');
</script>

The neat trick is bricks.findIndex((b) => resolve(b)): resolve returns true for the first brick it actually pushed the ball out of, and findIndex stops right there, so exactly one brick is resolved and removed per update.

Tip: At 230 px/s the ball moves under 4 px per update and the bricks are 12 px tall, so it can't tunnel through them. If you later speed it up a lot, run the physics in smaller sub-steps (for example 4 × dt/4 per update) rather than making the bricks thicker.

Test yourself

A ball overlaps a brick by 6 px horizontally and 2 px vertically. Which face did it come through?

  1. The left or right face
  2. The top or bottom face
  3. A corner, always
  4. It can't be known

Why push the ball out by the overlap before changing its velocity?

  1. So the next update doesn't detect the same collision again
  2. To make the ball faster
  3. Because canvas can't draw overlapping shapes
  4. It isn't needed

With the paddle aiming rule, where should the ball hit the paddle to go straight up?

  1. The left end
  2. The centre
  3. The right end
  4. Anywhere