← Back to home
Tutorial series

Step 13. Collecting diamonds

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

When the hero touches the diamond, it will be considered collected and should disappear from the screen. How to determine the moment of collision? We already did this for the hero and platform in the GameScene.js class when we implemented the onCollisionStart method. Now let’s extend this method to check for the presence of a diamond object and handle such a collision:

export class GameScene extends Scene {
    // ...
    onCollisionStart(event) {
        // ...
        const diamond = colliders.find(body => body.gameDiamond);

        if (hero && diamond) {
            this.hero.collectDiamond(diamond.gameDiamond);
        }
    }
    // ...
}

We need to implement the collectDiamond method in the Hero.js class:

import * as Matter from 'matter-js';
import * as PIXI from "pixi.js";
import { App } from '../system/App';

export class Hero {
    constructor() {
        // ...
        this.score = 0;
    }
    collectDiamond(diamond) {
        ++this.score;
        Matter.World.remove(App.physics.world, diamond.body);
        diamond.sprite.destroy();
        diamond.sprite = null;
    }
    // ...
}

When collecting a diamond, we destroy its physical body and destroy the sprite itself. We also increase the hero’s score counter, which we will later display on the screen as a game score.