Gamedev Phaser Content Kit

Article 10: Collision detection

I hope you survived the previous lesson, it was quite intense. 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. This makes everything a lot easier:

function update() {
    game.physics.arcade.collide(ball, paddle);
    game.physics.arcade.collide(ball, bricks, ballHitBrick);
    paddle.x = game.input.x || game.world.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 the collision occurs. Create that function just before the closing </script> tag:

function ballHitBrick(ball, brick) {
    brick.kill();
}

As you can see thanks to Phaser there are two parameters passed to the function - first one is the ball which we explicitly defined in the collide method, and the second one is the single brick from the bricks group that the ball is colliding with. When we have the reference to it, we can then kill the brick which will remove it from the screen.

Sorry to disappoint you if you expected to have more calculations for collision detection on your own if you coded it in pure JavaScript. That's the beauty of using the framework - you can leave a lot of boring code to it, just like in our case, and focus on the most fun and interesting parts of making a game.

Compare your code

You can check the finished code for this lesson for yourself in the live demo below, and play with it to understand better how it works:

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 keep it as the score.