← Back to home
Tutorial series

Step 15. Restarting the game when the hero falls

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

We will complete the development by restarting the game after the hero falls off the platform. You need to restart the game on the event of the death of the hero. Let’s start by adding a handler for such an event in the GameScene class:

export class GameScene extends Scene {
    createHero() {
        // ...
        this.hero.sprite.once("die", () => {
            App.scenes.start("Game");
        });
    }
}

We know that calling the start method of the ScenesManager class will automatically call the destroy method of the current scene before starting a new scene. Thus, in this method, it is necessary to implement all the logic for closing the scene. Namely: destroy all objects on the stage and disable all event handlers. Let’s do it:

destroy() {
    Matter.Events.off(App.physics, 'collisionStart', this.onCollisionStart.bind(this));
    App.app.ticker.remove(this.update, this);
    this.bg.destroy();
    this.hero.destroy();
    this.platfroms.destroy();
    this.labelScore.destroy();
}

Now we implement the destroy method in each of the listed objects. Background.js

destroy() {
    this.container.destroy();
}

Platforms.js

destroy() {
    this.platforms.forEach(platform => platform.destroy());
    this.container.destroy();
}

Platform.js

destroy() {
    Matter.World.remove(App.physics.world, this.body);
    this.diamonds.forEach(diamond => diamond.destroy());
    this.container.destroy();
}

Diamond.js

destroy() {
    if (this.sprite) {
        App.app.ticker.remove(this.update, this);
        Matter.World.remove(App.physics.world, this.body);
        this.sprite.destroy();
        this.sprite = null;
    }
}

Finally, let’s finish by firing the die event on the Hero class:

Hero.js

update() {
    // ...
    if (this.sprite.y > window.innerHeight) {
        this.sprite.emit("die");
    }
}

destroy() {
    App.app.ticker.remove(this.update, this);
    Matter.World.add(App.physics.world, this.body);
    this.sprite.destroy();
}