Right now the hero can only perform jump 2 jumps because the this.jumpIndex counter never resets.
And at what point should this counter be reset to give the hero the opportunity for a new double jump?
That is the moment when hero touches the platform. This means that the hero has landed on the ground and the previous jump is completed.
How can we track the collision of the hero and the platform? To do this, we will again use the physics engine and the interaction of the physical bodies of the hero and the platform.
The Matter physics engine will fire a collision event when two physics bodies collide. So we need to listen for this event.
Let’s do this in the GameScene class:
import * as Matter from 'matter-js';
import { App } from '../system/App';
//...
export class GameScene extends Scene {
create() {
//...
this.setEvents();
}
setEvents() {
Matter.Events.on(App.physics, 'collisionStart', this.onCollisionStart.bind(this));
}
onCollisionStart(event) {
const colliders = [event.pairs[0].bodyA, event.pairs[0].bodyB];
const hero = colliders.find(body => body.gameHero);
const platform = colliders.find(body => body.gamePlatform);
if (hero && platform) {
this.hero.stayOnPlatform(platform.gamePlatform);
}
}
// ...
}
The onCollisionStart method will run automatically when the collisionStart event occurs, which means that a collision of physical bodies has occurred.
In this method, we get physical bodies that interact with each other.
Since we created the gameHero and gamePlatform properties in the physical body objects of the hero and platform in advance, we can now check for the presence of such properties and determine from them what kind of body is involved in the collision.
Finally, if we got both a hero and a platform, we’ll call the stayOnPlatform method to set the hero on the platform.
Let’s implement this method in the Hero class:
export class Hero {
// ...
stayOnPlatform(platform) {
this.platform = platform;
this.jumpIndex = 0;
}
All we need to do in it is reset the counter and set the current platform to the this.platform property.
And now we can improve the code of the startJump method by adding an additional check whether the hero is currently on the platform. If a jump is possible, then the this.platform property should be reset.
startJump() {
if (this.platform || this.jumpIndex === 1) {
++this.jumpIndex;
this.platform = null;
Matter.Body.setVelocity(this.body, { x: 0, y: -this.dy });
}
}