class ExampleScene extends Phaser.Scene {
// ... previous property definitions ...
bricks;
// ... rest of the class ...
}Build the brick field / notebook
Build the brick field
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
class ExampleScene extends Phaser.Scene {
// ...
preload() {
// ...
this.load.image("brick", "img/brick.png");
}
// ...
}class ExampleScene extends Phaser.Scene {
// ...
create() {
// ...
this.initBricks();
}
// ...
}class ExampleScene extends Phaser.Scene {
// ...
initBricks() {
const bricksLayout = {
width: 50,
height: 20,
count: {
row: 3,
col: 7,
},
offset: {
top: 50,
left: 60,
},
padding: 10,
};
}
}this.bricks = this.add.group();for (let c = 0; c < bricksLayout.count.col; c++) {
for (let r = 0; r < bricksLayout.count.row; r++) {
// create new brick and add it to the group
}
}for (let c = 0; c < bricksLayout.count.col; c++) {
for (let r = 0; r < bricksLayout.count.row; r++) {
const brickX = 0;
const brickY = 0;
const newBrick = this.add.sprite(brickX, brickY, "brick");
this.physics.add.existing(newBrick);
newBrick.body.setImmovable(true);
this.bricks.add(newBrick);
}
}const brickX =
c * (bricksLayout.width + bricksLayout.padding) + bricksLayout.offset.left;
const brickY =
r * (bricksLayout.height + bricksLayout.padding) + bricksLayout.offset.top;class ExampleScene extends Phaser.Scene {
// ...
update() {
this.physics.collide(this.ball, this.paddle);
this.physics.collide(this.ball, this.bricks, (ball, brick) =>
this.hitBrick(ball, brick),
);
this.paddle.x = this.input.x || this.scale.width * 0.5;
// ...
}
// ...
}class ExampleScene extends Phaser.Scene {
// ...
hitBrick(ball, brick) {
brick.destroy();
}
}