This lesson was updated. Reset to the new version?
This browser isn't keeping your edits, so they're lost when you leave the page.
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 upelse if the ball was below the brick: put the ball under the brick and send it downelse if the ball was left of the brick: put the ball left of the brick and send it leftelse if the ball was right of the brick: put the ball right of the brick and send it rightAbove 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.jsyou’ll notice that we’ve added another method,generateBallSprites(), to extract the brick sprites from the sprite sheet. -
Brick.jscreates our brick class:constructor()initializes a brick. Importantly, we include aninPlayflag 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 theinPlayflag tofalse.render()renders a brick to the screen.
-
PlayState.jsgets its bricks from a new class,LevelMakerinsrc/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.jsstores 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:
Bblue,Ggreen,Rred,Ppurple, andYyellow. Thecoloursobject turns each letter into the colour number thatBrickuses 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.
- The letters are colours:
-
createMap()insrc/LevelMaker.jsturns a design into bricks. It loops over the rows, then over the characters in each row, and skips the dots:src/LevelMaker.js 79for (let row = 0; row < design.length; row++) {80const characters = design[row];8182// Centre the row on the screen.83const xOffset = (CANVAS_WIDTH - characters.length * brickWidth) / 2;8485for (let column = 0; column < characters.length; column++) {86const character = characters[column];8788// Leave a gap where the design has a dot.89if (character === ".") {90continue;91}9293const brick = new Brick(94xOffset + column * brickWidth,95brickHeight * 2 + row * brickHeight,96);9798brick.colour = colours[character];99100bricks.push(brick);101}102}- The column number sets the brick’s
x, and the row number sets itsy.brickHeight * 2leaves a gap above the top row for the ball to bounce around in. xOffsetcentres a row that’s shorter than the screen.
- The column number sets the brick’s
-
handlePaddleCollision()insrc/Ball.jsfollows the paddle algorithm above:src/Ball.js 75handlePaddleCollision(paddle) {76const maxBounceDx = 200; // Sideways speed when the ball lands on a paddle end.77const paddleSpin = 0.3; // How much of the paddle's speed passes to the ball.7879const ballCentre = this.x + this.width / 2;80const paddleCentre = paddle.x + paddle.width / 2;8182// -1 at the paddle's left end, 0 in the middle, 1 at the right end.83let hitPosition = (ballCentre - paddleCentre) / (paddle.width / 2);84hitPosition = Math.max(-1, Math.min(1, hitPosition));8586// Put the ball on top of the paddle and send it up.87this.y = paddle.y - this.height;88this.dy = -Math.abs(this.dy);8990this.dx = hitPosition * maxBounceDx;9192// A moving paddle drags the ball along with it a little.93this.dx += paddle.dx * paddleSpin;94}ballCentre - paddleCentreis 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()andMath.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.dxis 0 when the paddle stands still, so spin only applies while the player moves.- Raise
maxBounceDxfor flatter shots off the ends, and raisepaddleSpinfor stronger spin.
-
update()insrc/Ball.jssaves the ball’s position before moving it:src/Ball.js 156update(dt) {157// Remember where the ball was before it moves, for handleBrickCollision().158this.previousX = this.x;159this.previousY = this.y; -
handleBrickCollision()insrc/Ball.jsfollows the pseudocode above. Eachwasconstant compares an edge of the ball’s previous position with the opposite edge of the brick. After the bounce, it scalesdyby 1.02 to speed up the game. It stops speeding up atmaxSpeed, because a ball that moves too far in one frame can skip past a brick without ever overlapping it:src/Ball.js 103handleBrickCollision(brick) {104const wasAbove = this.previousY + this.height <= brick.y;105const wasBelow = this.previousY >= brick.y + brick.height;106const wasLeft = this.previousX + this.width <= brick.x;107const wasRight = this.previousX >= brick.x + brick.width;108109// Top and bottom come first so hits at the seam between two bricks bounce vertically.110if (wasAbove) {111this.y = brick.y - this.height;112this.dy = -Math.abs(this.dy); // Send the ball up.113} else if (wasBelow) {114this.y = brick.y + brick.height;115this.dy = Math.abs(this.dy); // Send the ball down.116} else if (wasLeft) {117this.x = brick.x - this.width;118this.dx = -Math.abs(this.dx); // Send the ball left.119} else if (wasRight) {120this.x = brick.x + brick.width;121this.dx = Math.abs(this.dx); // Send the ball right.122}123124// Speed up a little with each brick, up to a limit so the ball can't skip through bricks.125const maxSpeed = 350;126127if (Math.abs(this.dy) < maxSpeed) {128this.dy *= 1.02;129}130} -
update()insrc/states/PlayState.jsloops over the bricks withfor...ofinstead offorEach(), becausebreakonly works in a loop:src/states/PlayState.js 56for (const brick of this.bricks) {57if (brick.inPlay && this.ball.didCollide(brick)) {58// Call the brick's hit function, which removes it from play.59brick.hit();6061this.ball.handleBrickCollision(brick);6263// Only bounce off one brick per frame, or two bricks side by side would cancel out.64break;65}66}