TExcelTAD
Home › 2D Games with JavaScript & Canvas › Breakout 1: Paddle, Ball & Bricks

Breakout 1: Paddle, Ball & Bricks

Breakout takes Pong's ball and paddle and adds the thing that makes it a different game: many objects that disappear when hit. That brings new problems: storing dozens of bricks, checking the ball against all of them, and removing them safely. Over four lessons we'll build a complete Breakout with levels, lives and sound.

Lesson What we add
Breakout 1 (this one) paddle, ball on a launcher, a grid of bricks
Breakout 2 correct bounces off brick sides and corners, paddle aiming
Breakout 3 levels from strings, tough bricks, lives, win and lose
Breakout 4 sound effects with Web Audio

Building the brick grid

The bricks are a plain array of objects. Two nested loops lay them out in rows and columns; the numbers below center a 10 × 5 wall in our 480-pixel court:

js
const COLS = 10, ROWS = 5, BRICK_W = 44, BRICK_H = 12, GAP = 2;
const LEFT = (W - (COLS * (BRICK_W + GAP) - GAP)) / 2;   // 11 px margin on each side
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), row });
  }
}

You can check that layout math without drawing anything:

js · try it yourself
const W = 480, COLS = 10, ROWS = 5, BRICK_W = 44, BRICK_H = 12, GAP = 2;
const LEFT = (W - (COLS * (BRICK_W + GAP) - GAP)) / 2;

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) });
  }
}

const last = bricks[bricks.length - 1];
console.log("bricks:", bricks.length);
console.log("left margin:", LEFT);
console.log("first:", bricks[0], "last:", last);
console.log("right margin:", W - (last.x + BRICK_W));
bricks: 50
left margin: 11
first: { x: 11, y: 30 } last: { x: 425, y: 86 }
right margin: 11

Launching the ball

At the start of each life the ball sits on the paddle and moves with it. Pressing Space launches it. One flag, stuck, handles this:

js
if (ball.stuck) {
  ball.x = paddle.x + PADDLE_W / 2 - ball.size / 2;   // ride on the paddle
  ball.y = paddle.y - ball.size;
  if (pressed.has('Space')) { ball.stuck = false; ball.vx = 120; ball.vy = -BALL_SPEED; }
  return;
}

Hitting and removing bricks

Each update we look for one brick the ball overlaps. If we find it, we remove it from the array with splice and flip the ball's vertical direction:

js
const i = bricks.findIndex((b) => overlaps(ball, b));
if (i !== -1) {
  bricks.splice(i, 1);
  ball.vy = -ball.vy;
}

Why only one brick per update? If the ball touches two neighbouring bricks at once and we flipped vy for each, the two flips would cancel out and the ball would plough on through the wall. Handling the first hit and stopping is the simple, robust choice.

Note: Never remove items from an array while a for…of or forEach loop is walking it: the loop skips the element that slides into the removed slot. findIndex first, then splice, is safe. With many objects, a common alternative is to mark them dead = true and filter them out once per frame.

Step 1: playable

Click, then ←/→ (or A/D) to move and Space to launch:

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 1: paddle, ball and a wall of bricks ----
const PADDLE_W = 64, PADDLE_H = 8, PADDLE_SPEED = 320, BALL_SPEED = 230;
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), row });
  }
}

function overlaps(b, r) {
  return b.x < r.x + BRICK_W && b.x + b.size > r.x && b.y < r.y + BRICK_H && b.y + b.size > r.y;
}

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; ball.vx = 120; ball.vy = -BALL_SPEED; }
    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: a plain bounce for now (aiming comes in step 2).
  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;
    ball.vy = -Math.abs(ball.vy);
  }

  // Bricks: handle at most one hit per update.
  const i = bricks.findIndex((b) => overlaps(ball, b));
  if (i !== -1) {
    bricks.splice(i, 1);
    ball.vy = -ball.vy;
  }

  if (ball.y > H) ball.stuck = true;          // missed: back on the paddle
}

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), BRICK_W, BRICK_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>

Play for a while and you'll spot a bug: when the ball clips the side of a brick, it still bounces vertically and slides along the wall in a strange way. Fixing that properly is the subject of Breakout 2.

Test yourself

Why does the game handle at most one brick hit per update?

  1. To save CPU
  2. Two hits flipping vy twice would cancel out and the ball would pass through
  3. findIndex can only find one element
  4. Bricks can't overlap

What's wrong with calling bricks.splice(i, 1) inside bricks.forEach(...)?

  1. Nothing
  2. The element that slides into slot i is skipped by the loop
  3. splice doesn't work on arrays of objects
  4. It throws an error

How does the ball "ride" on the paddle before launch?

  1. It is drawn inside the paddle
  2. While stuck is true, each update sets its position from the paddle's position
  3. It has the same velocity as the paddle
  4. With a CSS animation