The score
This is the 11th step out of 16 of the Gamedev Phaser tutorial. In this article, we'll add a scoring system to our game. Having a score can also make the game more interesting—you can try to beat your own high score, or your friend's.
We will use a separate property for storing the score and Phaser's text()
method to print it out onto the screen.
New properties
Add two new properties right after the previously defined ones:
class ExampleScene extends Phaser.Scene {
// ... previous property definitions ...
scoreText;
score = 0;
// ... rest of the class ...
}
Adding score text to the game display
Now add this line at the end of the create()
method:
this.scoreText = this.add.text(5, 5, "Points: 0", {
font: "18px Arial",
color: "#0095dd",
});
The text()
method can take four parameters:
- The x and y coordinates to draw the text at.
- The actual text that will be rendered.
- The font style to render the text with.
The last parameter looks very similar to CSS styling. In our case, the score text will be blue, sized at 18 pixels, and use the Arial font.
Updating the score when bricks are destroyed
We will increase the number of points every time the ball hits a brick and update the scoreText
to display the current score. This can be done using the setText()
method—add the two new lines seen below to the hitBrick()
method:
class ExampleScene extends Phaser.Scene {
// ...
hitBrick(ball, brick) {
brick.destroy();
this.score += 10;
this.scoreText.setText(`Points: ${this.score}`);
}
}
That's it for now—reload your index.html
and check that the score updates on every brick hit.
Compare your code
Here's what you should have so far, running live. To view its source code, click the "Play" button.
Next steps
We now have a scoring system, but what's the point of playing and keeping score if you can't win? Let's see how we can add a victory state, allowing us to win the game.