Having a score can boost player's interest in the game - you can try to beat your own or your friend's highscore and play the game again and again. To make it work in our game we will use separate variable for storing the score and Phaser's text element to print it out on the screen. Add those two variables right after the previously defined ones:
// ... var scoreText; var score = 0;
Now add this line at the end of the create
function:
scoreText = game.add.text(5, 5, 'Points: 0', { font: '18px Arial', fill: '#0095DD' });
As you can see the text element can take four parameters: x and y position, the actual text that will be rendered and the font style - the last parameter looks very similar to CSS styling. In our case the score text will be blue and will have 18 pixels using the Arial font. We will increase the number of points every time the ball hits the brick and update the text with the current value using the setText
method:
function ballHitBrick(ball, brick) { brick.kill(); score += 10; scoreText.setText('Points: '+score); }
That's it - the score is now added on every hit and updated on the screen.
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:
We have the score already, but what's the point of playing and keeping the score if you can't win? Let's see how we can make it work to win the game.