As we already know, all game objects that need to handle physics interactions (such as collision) need to create physics bodies and add them to the physics engine for processing.
We have already created a physical body for the hero and the platforms, and thus have the opportunity to handle the collision of the hero with the platform.
The player will be able to collect diamonds when they are touched by the hero’s sprite while jumping. This means that diamonds also need to create a physical body. Let’s improve the code in the Diamond class:
export class Diamond {
constructor(x, y) {
this.createSprite(x, y);
}
createSprite(x, y) {
this.sprite = App.sprite("diamond");
this.sprite.x = x;
this.sprite.y = y;
}
createBody() {
this.body = Matter.Bodies.rectangle(this.sprite.width / 2 + this.sprite.x + this.sprite.parent.x, this.sprite.height / 2 + this.sprite.y + this.sprite.parent.y, this.sprite.width, this.sprite.height, {friction: 0, isStatic: true, render: { fillStyle: '#060a19' }});
this.body.gameDiamond = this;
this.body.isSensor = true;
Matter.World.add(App.physics.world, this.body);
}
}
Here we created the physical body in the same way as we did for the platform and the hero. We used a rectangle at the sprite coordinates and the dimensions of the diamond sprite. As usual, we have stored a reference to the diamond object in the physical body object in order to access the diamond at the time of the collision events.
In addition, we have set the this.body.isSensor property to true.
This way, the hero sprite will be able to pass through the diamond image, unlike the platform, which should not pass the sprite through itself.
It remains to call the createBody method after the diamond is added as a child element to the platform container in the Platform.js class:
createDiamonds() {
const y = App.config.diamonds.offset.min + Math.random() * (App.config.diamonds.offset.max - App.config.diamonds.offset.min);
for (let i = 0; i < this.cols; i++) {
if (Math.random() < App.config.diamonds.chance) {
this.createDiamond(this.tileSize * i, -y);
}
}
}
createDiamond(x, y) {
const diamond = new Diamond(x, y);
this.container.addChild(diamond.sprite);
diamond.createBody();
this.diamonds.push(diamond);
}