Reset this lesson?

Your edits to this lesson are deleted and its starting files load again.

Breakout-3 renders bricks onto the screen. It implements bouncing behavior for the ball upon a collision with a brick. It also fixes our previous naive implementation of bouncing behavior between the ball and the paddle.

Important Algorithms

handlePaddleCollision() in src/Ball.js lets the player aim the ball by choosing where it lands on the paddle. The landing spot becomes a number from -1 to 1. It’s -1 at the paddle’s left end, 0 in the middle, and 1 at the right end. The ball’s dx is that number multiplied by the sideways speed at the ends, so the middle sends the ball straight up and the ends send it out at a shallow angle. Measuring from -1 to 1 instead of in pixels gives the same angles on every paddle size.

A moving paddle also adds some of its own speed to the ball as spin. Hitting the ball while moving right pushes it further right, and hitting it while moving left pulls it back.

For brick collision, handleBrickCollision() in src/Ball.js works out which side of the brick the ball came through. Once the ball is inside the brick, its current position can’t answer that. So update() in src/Ball.js saves the ball’s position in previousX and previousY before each move, which says where the ball was before it entered the brick:

if the ball was above the brick:
put the ball on top of the brick and send it up
else if the ball was below the brick:
put the ball under the brick and send it down
else if the ball was left of the brick:
put the ball left of the brick and send it left
else if the ball was right of the brick:
put the ball right of the brick and send it right

Above and below are checked first. When the ball hits the seam between two bricks in a row, it was below both of them on the previous frame, so it bounces down off the row. A ball that hits a brick right on its corner was both above (or below) and beside it, so it bounces vertically too.

Moving the ball back outside the brick stops it from still overlapping the brick on the next frame and bouncing a second time. The new velocity uses Math.abs() instead of flipping the sign. Flipping dy twice sends the ball back the way it came, but -Math.abs(this.dy) always points up, however many times it runs.

update() in src/states/PlayState.js stops checking bricks after the first hit with break. Without it, a ball touching two bricks side by side flips dy twice, so it carries straight on and destroys both bricks.

Important Code

  • In SpriteManager.js you’ll notice that we’ve added another method, generateBallSprites(), to extract the brick sprites from the sprite sheet.

  • Brick.js creates our brick class:

    • constructor() initializes a brick. Importantly, we include an inPlay flag to serve as a signal for whether a brick is still in play or if it should disappear from the screen. In the context of this Breakout game, this is an effective shortcut, but do note that in larger programs, it would be better practice to free memory that is not being used instead of just hiding it from view.
    • hit() hides a brick by toggling the inPlay flag to false.
    • render() renders a brick to the screen.
  • PlayState.js gets its bricks from a new class, LevelMaker in src/LevelMaker.js. It also checks for collisions between the ball and the bricks, hiding bricks as needed, and renders the “in play” bricks to the screen.

  • src/LevelMaker.js stores each level as a list of strings, one string per row of bricks. Each character is one brick, and a dot is a gap:

    src/LevelMaker.js
    10
    // Stripes, with a chimney up the middle.
    11
    [
    12
    "RRRRRRRRRRRRR",
    13
    "YYYYYYYYYYYYY",
    14
    "GGGGGG.GGGGGG",
    15
    "BBBBBB.BBBBBB",
    16
    ],
    • The letters are colours: B blue, G green, R red, P purple, and Y yellow. The colours object turns each letter into the colour number that Brick uses to pick its sprite.
    • A row holds up to 13 bricks, which fills the screen from side to side.
    • Writing levels this way means the code looks like the level. Change a letter, and that brick changes colour in the game.
  • createMap() in src/LevelMaker.js turns a design into bricks. It loops over the rows, then over the characters in each row, and skips the dots:

    src/LevelMaker.js
    79
    for (let row = 0; row < design.length; row++) {
    80
    const characters = design[row];
    81
    82
    // Centre the row on the screen.
    83
    const xOffset = (CANVAS_WIDTH - characters.length * brickWidth) / 2;
    84
    85
    for (let column = 0; column < characters.length; column++) {
    86
    const character = characters[column];
    87
    88
    // Leave a gap where the design has a dot.
    89
    if (character === ".") {
    90
    continue;
    91
    }
    92
    93
    const brick = new Brick(
    94
    xOffset + column * brickWidth,
    95
    brickHeight * 2 + row * brickHeight,
    96
    );
    97
    98
    brick.colour = colours[character];
    99
    100
    bricks.push(brick);
    101
    }
    102
    }
    • The column number sets the brick’s x, and the row number sets its y. brickHeight * 2 leaves a gap above the top row for the ball to bounce around in.
    • xOffset centres a row that’s shorter than the screen.
  • handlePaddleCollision() in src/Ball.js follows the paddle algorithm above:

    src/Ball.js
    75
    handlePaddleCollision(paddle) {
    76
    const maxBounceDx = 200; // Sideways speed when the ball lands on a paddle end.
    77
    const paddleSpin = 0.3; // How much of the paddle's speed passes to the ball.
    78
    79
    const ballCentre = this.x + this.width / 2;
    80
    const paddleCentre = paddle.x + paddle.width / 2;
    81
    82
    // -1 at the paddle's left end, 0 in the middle, 1 at the right end.
    83
    let hitPosition = (ballCentre - paddleCentre) / (paddle.width / 2);
    84
    hitPosition = Math.max(-1, Math.min(1, hitPosition));
    85
    86
    // Put the ball on top of the paddle and send it up.
    87
    this.y = paddle.y - this.height;
    88
    this.dy = -Math.abs(this.dy);
    89
    90
    this.dx = hitPosition * maxBounceDx;
    91
    92
    // A moving paddle drags the ball along with it a little.
    93
    this.dx += paddle.dx * paddleSpin;
    94
    }
    • ballCentre - paddleCentre is how far the ball landed from the middle of the paddle, in pixels. Dividing by half the paddle’s width turns that into the -1 to 1 range.
    • The ball’s edge can hang past the end of the paddle, which would give a number past 1 or -1. Math.max() and Math.min() clamp it back into range.
    • Placing the ball on top of the paddle stops it from overlapping the paddle on the next frame, the same as with bricks. -Math.abs(this.dy) always sends the ball up.
    • paddle.dx is 0 when the paddle stands still, so spin only applies while the player moves.
    • Raise maxBounceDx for flatter shots off the ends, and raise paddleSpin for stronger spin.
  • update() in src/Ball.js saves the ball’s position before moving it:

    src/Ball.js
    156
    update(dt) {
    157
    // Remember where the ball was before it moves, for handleBrickCollision().
    158
    this.previousX = this.x;
    159
    this.previousY = this.y;
  • handleBrickCollision() in src/Ball.js follows the pseudocode above. Each was constant compares an edge of the ball’s previous position with the opposite edge of the brick. After the bounce, it scales dy by 1.02 to speed up the game. It stops speeding up at maxSpeed, because a ball that moves too far in one frame can skip past a brick without ever overlapping it:

    src/Ball.js
    103
    handleBrickCollision(brick) {
    104
    const wasAbove = this.previousY + this.height <= brick.y;
    105
    const wasBelow = this.previousY >= brick.y + brick.height;
    106
    const wasLeft = this.previousX + this.width <= brick.x;
    107
    const wasRight = this.previousX >= brick.x + brick.width;
    108
    109
    // Top and bottom come first so hits at the seam between two bricks bounce vertically.
    110
    if (wasAbove) {
    111
    this.y = brick.y - this.height;
    112
    this.dy = -Math.abs(this.dy); // Send the ball up.
    113
    } else if (wasBelow) {
    114
    this.y = brick.y + brick.height;
    115
    this.dy = Math.abs(this.dy); // Send the ball down.
    116
    } else if (wasLeft) {
    117
    this.x = brick.x - this.width;
    118
    this.dx = -Math.abs(this.dx); // Send the ball left.
    119
    } else if (wasRight) {
    120
    this.x = brick.x + brick.width;
    121
    this.dx = Math.abs(this.dx); // Send the ball right.
    122
    }
    123
    124
    // Speed up a little with each brick, up to a limit so the ball can't skip through bricks.
    125
    const maxSpeed = 350;
    126
    127
    if (Math.abs(this.dy) < maxSpeed) {
    128
    this.dy *= 1.02;
    129
    }
    130
    }
  • update() in src/states/PlayState.js loops over the bricks with for...of instead of forEach(), because break only works in a loop:

    src/states/PlayState.js
    56
    for (const brick of this.bricks) {
    57
    if (brick.inPlay && this.ball.didCollide(brick)) {
    58
    // Call the brick's hit function, which removes it from play.
    59
    brick.hit();
    60
    61
    this.ball.handleBrickCollision(brick);
    62
    63
    // Only bounce off one brick per frame, or two bricks side by side would cancel out.
    64
    break;
    65
    }
    66
    }
Powered by WebContainers
Files
Preparing Environment