Завершим разработку перезапуском игры после падения героя с платформы. Перезапуск нужен по событию смерти героя. Начнём с обработчика этого события в GameScene:
export class GameScene extends Scene {
createHero() {
// ...
this.hero.sprite.once("die", () => {
App.scenes.start("Game");
});
}
}
Вызов start у ScenesManager автоматически вызывает destroy текущей сцены перед запуском новой. Поэтому в destroy нужно реализовать всю логику закрытия сцены: уничтожить объекты и отключить обработчики событий. Сделаем это:
destroy() {
Matter.Events.off(App.physics, 'collisionStart', this.onCollisionStart.bind(this));
App.app.ticker.remove(this.update, this);
this.bg.destroy();
this.hero.destroy();
this.platfroms.destroy();
this.labelScore.destroy();
}
Теперь реализуем destroy в каждом перечисленном объекте. Background.js
destroy() {
this.container.destroy();
}
Platforms.js
destroy() {
this.platforms.forEach(platform => platform.destroy());
this.container.destroy();
}
Platform.js
destroy() {
Matter.World.remove(App.physics.world, this.body);
this.diamonds.forEach(diamond => diamond.destroy());
this.container.destroy();
}
Diamond.js
destroy() {
if (this.sprite) {
App.app.ticker.remove(this.update, this);
Matter.World.remove(App.physics.world, this.body);
this.sprite.destroy();
this.sprite = null;
}
}
Завершим отправкой события die в классе Hero:
Hero.js
update() {
// ...
if (this.sprite.y > window.innerHeight) {
this.sprite.emit("die");
}
}
destroy() {
App.app.ticker.remove(this.update, this);
Matter.World.add(App.physics.world, this.body);
this.sprite.destroy();
}