Gamedev Phaser Content Kit

Article 05: Physics

For the proper use of collision detection between objects in our game we will need to have physics. Phaser is bundled with three different physics engines: Arcade Physics, P2 and Ninja Physics with the fourth Box2D available as a commercial plugin. For simple games, which in our case is the Breakout game, we can use the Arcade Physics engine. We don't need any heavy geometry calculations, after all it's just a ball bouncing off the walls and bricks.

First, let's initialize the Arcade Physics in our game. Write down the physics.startSystem method at the beginning of the create function:

game.physics.startSystem(Phaser.Physics.ARCADE);

Next, we need to enable our ball for the physics system - Phaser objects are not enabled for that by default:

game.physics.enable(ball, Phaser.Physics.ARCADE);

Then, if we want to move our ball on the screen, we can set velocity to its body:

ball.body.velocity.set(150, 150);

Remember to remove our old method of adding values to x and y in the update function:

function update() {
    ball.x += 1;
    ball.y += 1;
}

All the code should look like this:

var ball;

function preload() {
    game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;
    game.stage.backgroundColor = '#eee';
    game.load.image('ball', 'img/ball.png');
}

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);
    ball = game.add.sprite(50, 50, 'ball');
    game.physics.enable(ball, Phaser.Physics.ARCADE);
    ball.body.velocity.set(150, 150);
}

function update() {
}

The ball is now moving constantly in given direction, because the physics engine have the gravity and friction defaults set to zero. Adding gravity would result in the ball falling down while friction would eventually stop the ball after some time.

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

Now we can move to the next lesson and see how to make the ball bounce off the walls.