import {compose, merge} from '@avocado/core'; import {Vector} from '@avocado/math'; import {StateProperty, Trait} from '../trait'; import {Entity} from '..'; const decorate = compose( StateProperty('isSpawning', { track: true, }), StateProperty('maxSpawns'), ); export class Spawner extends decorate(Trait) { static defaultParams() { return { spawns: {}, }; } static defaultState() { return { isSpawning: true, maxSpawns: Infinity, }; } static type() { return 'spawner'; } destroy() { this.children = []; } constructor(entity, params, state) { super(entity, params, state); this.children = []; this.spawnJSONs = this.params.spawns; } listeners() { return { dying: () => { this.isSpawning = false; }, }; } methods() { return { killAllChildren: () => { for (let i = 0; i < this.children.length; i++) { this.children[i].destroyGently(); } }, spawn: (key, json = {}) => { if (!this.entity.is('listed')) { return; } if (this.maxSpawns <= this.children.length) { return; } const spawnJSON = this.spawnJSONs[key]; if (!spawnJSON) { return; } const list = this.entity.list; Entity.loadOrInstance(merge(spawnJSON, json)).then((spawn) => { this.children.push(spawn); spawn.once('destroy', () => { const index = this.children.indexOf(spawn); this.children.splice(index, 1); }) list.addEntity(spawn); }); }, }; } }