Collision detection - Game development 编辑

This is the 10th step out of 16 of the Gamedev Phaser tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson10.html.

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() function that checks for collision detection between ball and bricks, as shown below:

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 a collision occurs — ballHitBrick(). Create this new function as the bottom of your code, just before the closing </script> tag, as follows:

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

And that's it! Reload your code and you should see the new collision detection working just as required.

Thanks to Phaser there are two parameters passed to the function — the 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. Inside the function we remove the brick in question from the screen by running the kill() method on it.

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

You can check the finished code for this lesson 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 increment the score as a result.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:121 次

字数:4017

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文