We will give the hero the opportunity to jump twice. This means that after the first jump, the hero will be able to perform another jump while he’s in the air. Then he must land on the platform to make the next jump.
Let’s make the hero jump by pressing anywhere in the screen.
We will listen to the pointerdown event in the GameScene class:
export class GameScene extends Scene {
// ...
createHero() {
// ...
this.container.interactive = true;
this.container.on("pointerdown", () => {
this.hero.startJump();
});
}
// ...
}
As you can see, now we need to implement the startJump method in the Hero class:
export class Hero {
constructor() {
// ...
this.dy = App.config.hero.jumpSpeed;
this.maxJumps = App.config.hero.maxJumps;
this.jumpIndex = 0;
}
startJump() {
if (this.jumpIndex < this.maxJumps) {
++this.jumpIndex;
Matter.Body.setVelocity(this.body, { x: 0, y: -this.dy });
}
}
// ...
}
The jumpIndex counter limits the number of jumps until the next touch of the platform.
The maximum possible number of jumps is indicated in the property this.maxJumps.
We use the physical engine to set the speed of the hero’s physical body. For a jump, we need to move it only along the axis y up. This means that we need to set a negative displacement for the y coordinate, which is set in the this.dy property.
And finally, we take out the values of the jump speed and the number of jumps into the global config for the convenience of configuration:
export const Config = {
// ...
hero: {
jumpSpeed: 15,
maxJumps: 2,
//...
}
};