monsterplex/src/systems/KidManager.js

55 lines
1.4 KiB
JavaScript

import Phaser from 'phaser';
import { GFORCE } from '../config.js';
import Kid from '../entities/Kid.js';
export default class KidManager {
constructor(scene, bus, kidsAboard) {
this.scene = scene;
this.bus = bus;
this.total = kidsAboard;
this.kids = [];
this._lastEjectTime = -Infinity;
for (let i = 0; i < kidsAboard; i++) {
this.kids.push(new Kid(scene, bus, i));
}
this._onGForceExceeded = this._onGForceExceeded.bind(this);
scene.events.on('gforce-exceeded', this._onGForceExceeded);
}
get kidsAboardCount() {
return this.kids.filter((kid) => kid.state === 'aboard').length;
}
_onGForceExceeded({ gForce }) {
const now = this.scene.time.now;
if (now - this._lastEjectTime < GFORCE.ejectCooldownMs) return;
const aboard = this.kids.filter((kid) => kid.state === 'aboard');
if (aboard.length === 0) return;
this._lastEjectTime = now;
const kid = Phaser.Utils.Array.GetRandom(aboard);
kid.eject(this.bus.chassis.body.velocity, gForce);
this.scene.events.emit('kid-ejected', {
kidsAboard: this.kidsAboardCount,
total: this.total,
});
if (this.kidsAboardCount === 0) {
this.scene.events.emit('level-failed', { reason: 'all-kids-lost' });
}
}
update(time) {
for (const kid of this.kids) kid.update(time);
}
destroy() {
this.scene.events.off('gforce-exceeded', this._onGForceExceeded);
for (const kid of this.kids) kid.destroy();
}
}