Now that physics have been introduced, we can start implementing collision detection into the game — first we'll look at the walls.
The easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the
<canvas> element as walls and not let the ball move past them. In Phaser this can be easily accomplished using the
collideWorldsBound property. Add this line right after the existing
game.physics.enable() method call:
ball.body.collideWorldBounds = true;
Now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. To make this occur we have to set its bounciness. Add the following line below the previous one:
Try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area.
You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: