Gamedev Phaser Content Kit

Article 15: Buttons

Instead of starting the game right away we can leave that decision to the player by adding the Start button he can press. Before that, the game would wait for the input. We will need a variable storing the boolean value of whether or not the game is currently being played, and the second one for the button:

var playing = false;
var startButton;

We can load the button spritesheet the same way we loaded the ball's wobble animation:

game.load.spritesheet('button', 'img/button.png', 120, 40);

A single button frame is 120 pixels wide and 40 pixels high:

Button spritesheet

Adding the new button to the game is done by using the add.button method:

startButton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startGame, this, 1, 0, 2);
startButton.anchor.set(0.5);

We define the button's x and y position, the graphic asset name, callback function that will be executed when the button will be pressed, reference to this to have the execution context available, and the frames that will be used for the over, out and down events.

The over event is the same as hover, out is when the pointer moves out of the button and down is when the button is pressed. Now, to make it work we need to define the startGame function:

function startGame() {
    startButton.destroy();
    ball.body.velocity.set(150, -150);
    playing = true;
}

It removes the button, sets the ball's initial velocity and the playing variable to true. It works as expected, but we can still move the paddle when the game hasn't started yet. We can leave it as it is, but we can also take an advantage of the playing variable and make the paddle movable only when the game is on. To do that, adjust the update function to check that:

function update() {
    game.physics.arcade.collide(ball, paddle, ballHitPaddle);
    game.physics.arcade.collide(ball, bricks, ballHitBrick);
    if(playing) {
        paddle.x = game.input.x || game.world.width*0.5;
    }
}

That way the paddle is immovable after everything is loaded and prepared, but before the start of the actual game.

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

The last thing to add and make the gameplay even more interesting is some randomization in the way the ball bounces off the paddle.