By analogy with the platform, let’s create a physical body for the hero in the Hero.js file:
import * as Matter from 'matter-js';
// ...
export class Hero {
constructor() {
// ...
this.createBody();
App.app.ticker.add(this.update.bind(this));
}
// [07]
createBody() {
this.body = Matter.Bodies.rectangle(this.sprite.x + this.sprite.width / 2, this.sprite.y + this.sprite.height / 2, this.sprite.width, this.sprite.height, {friction: 0});
Matter.World.add(App.physics.world, this.body);
this.body.gameHero = this;
}
update() {
this.sprite.x = this.body.position.x - this.sprite.width / 2;
this.sprite.y = this.body.position.y - this.sprite.height / 2;
}
}
As well as for the platform we created a rectangle body in the position of the hero and in its dimensions.
Then we added the created body to the engine and saved a reference to the hero itself in the body object. We will need this later when processing collisions, when we will have access to the colliding physical bodies.
In addition, we have created an update method that is added to the PIXI ticker and will be called on every frame of the animation.
In it, we force the hero’s sprite to the position of his physical body in order to synchronize them. Thus, wherever the hero’s physical body is sent as a result of interaction with physical objects, the hero’s sprite will be placed in the same position.