Collision detection
This is the 10th step out of 16 of the Gamedev Phaser tutorial. Now onto the next challenge—the collision detection between the ball and the bricks. Luckily enough, we can use the physics engine to check collisions not only between single objects (like the ball and the paddle), but also between an object and the group.
Brick/Ball collision detection
The physics engine makes everything a lot easier—we just need to add two simple pieces of code. First, add a new line inside your update()
method that detects a collision between the ball and bricks, as shown below:
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;
// ...
}
// ...
}
The ball's position is calculated against the positions of all the bricks in the group. The third, optional parameter is the function executed when a collision occurs. This function is called by Phaser with two arguments—the first one is the ball, which we explicitly passed to the collide method, and the second one is the single brick from the bricks group that the ball is colliding with. Here we implement the behavior in a method called hitBrick()
. Create this new method at the end of the ExampleScene
class, just before the closing brace }
, as follows:
class ExampleScene extends Phaser.Scene {
// ...
hitBrick(ball, brick) {
brick.destroy();
}
}
And that's it! Reload your code, and you should see the new collision detection working just as required.
You would expect to have to write a lot more calculations of your own to implement collision detection when using pure JavaScript. That's the beauty of using the framework—you can leave a lot of boring code to Phaser, and focus on the most fun and interesting parts of making a game.
Compare your code
Here's what you should have so far, running live. To view its source code, click the "Play" button.
Next steps
We can hit the bricks and remove them, which is a nice addition to the gameplay already. It would be even better to count the destroyed bricks and increment the score as a result.