← Back to home
Tutorial series

Step 14. UI

Create a platformer with PixiJS Step 14 of 15 2 min read

Let’s display the player’s score on the screen. Let’s create the LabelScore class, which will be the successor of PIXI.Text:

import * as PIXI from "pixi.js";
import { App } from "../system/App";

export class LabelScore extends PIXI.Text {
    constructor() {
        super();
        this.x = App.config.score.x;
        this.y = App.config.score.y;
        this.anchor.set(App.config.score.anchor);
        this.style = App.config.score.style;
        this.renderScore();
    }

    renderScore(score = 0) {
        this.text = `Score: ${score}`;
    }
}

Let’s take out all the positioning and text style parameters in the global config Config.js:

export const Config = {
    score: {
        x: 10,
        y: 10,
        anchor: 0,
        style: {
            fontFamily: "Verdana",
            fontWeight: "bold",
            fontSize: 44,
            fill: ["#FF7F50"]
        }
    },
    // ...
};

Let’s create an instance of this class and add it to the game scene:

export class GameScene extends Scene {
    create() {
        // ...
        this.createUI();
    }

    createUI() {
        this.labelScore = new LabelScore();
        this.container.addChild(this.labelScore);
        this.hero.sprite.on("score", () => {
            this.labelScore.renderScore(this.hero.score);
        });
    }
}

As you can see, it remains to add the launch of the score event to the hero object at the time of collecting the diamond:

export class Hero {
    // ...
    collectDiamond(diamond) {
        // ...
        this.sprite.emit("score");
    }
}