Bounce off the walls
This is the 6th step out of 16 of the Gamedev Phaser tutorial. Now that physics have been introduced, we can start implementing collision detection into the game—first we'll look at the walls.
Bouncing off the world boundaries
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 setCollideWorldBounds()
method. Add this line right after the existing this.ball.body.setVelocity()
method call:
this.ball.body.setCollideWorldBounds(true, 1, 1);
The true
tells Phaser to enable collision detection with the world bounds, while the two 1
s are the bounce factor on the x and y axes, respectively. This means that when the ball hits a wall, it will bounce back with the same speed it had before hitting the wall. Try reloading index.html again—now you should see the ball bouncing off all the walls and moving inside the canvas area.
Compare your code
Here's what you should have so far, running live. To view its source code, click the "Play" button.
Next steps
This is starting to look more like a game now, but we can't control it in any way—it's high time we introduced the player paddle and controls.