Gamedev Phaser Content Kit

Article 06: Bounce off the walls

Now when the physics are introduced, we can start implementing collision detection into the game - first comes the walls. The easiest way to do it is to tell the framework that we want to treat boundaries of the Canvas element as walls and bounce the ball off of them. Add this line right after the place where we enabled the physics for the ball:

ball.body.collideWorldBounds = true;

Now the ball stops at the edge of the screen instead of disappearing, but it doesn't look like bouncing. To make it work we have to set its bounciness:

ball.body.bounce.set(1);

Now it works as expected - the ball bounces off all the walls and moves inside the world, our Canvas area.

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

It looks nice already, but we can't control the game in any way - it's the high time to introduce player paddle and controls.