In the game, the diamonds will be positioned above the platforms in such a way as to motivate the player to jump from the platform to collect them.
We will create diamonds for each platform in the corresponding class. Let’s create a certain number of diamond images above the platform:
// ...
export class Platform {
constructor(rows, cols, x) {
// ...
this.diamonds = [];
this.createDiamonds();
}
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) {
const diamond = new Diamond(this.tileSize * i, -y);
this.container.addChild(diamond.sprite);
this.diamonds.push(diamond);
}
}
}
// ...
}
Let’s loop through all the tiles of the platform and check the possibility of creating a diamond over each tile. The probability of creating a diamond over one tile is obtained from the property of the global config App.config.diamonds.chance.
If we need to create a diamond over this tile, then we will create an instance of the Diamond class. Let’s place the created object in the this.diamonds property and add it as a child element to the platform container.
Let’s add the settings for creating diamonds to the global config:
// ...
export const Config = {
// ...
diamonds: {
chance: 0.4,
offset: {
min: 100,
max: 200
}
}
}
The chance property indicates the probability of a diamond being generated on each specific platform tile. The offset object defines the allowable height range at which the diamond must be positioned above the platform.
It remains to implement the Diamond class. At the moment, we only implement in it the output of the diamond sprite:
import { App } from '../system/App';
export class Diamond {
constructor(x, y) {
this.sprite = App.sprite("diamond");
this.sprite.x = x;
this.sprite.y = y;
}
}