avocado-old/packages/entity/traits/spawner.trait.js

91 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-04-21 01:30:03 -05:00
import merge from 'lodash.merge';
import {compose} 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,
};
}
destroy() {
this.children = [];
}
2019-04-21 01:30:03 -05:00
initialize() {
this.children = [];
this.spawnJSONs = this.params.get('spawns').toJS();
}
listeners() {
return {
dying: () => {
this.isSpawning = false;
},
};
}
methods() {
return {
killAllChildren: () => {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
// Try kill...
if (child.is('alive')) {
2019-04-21 21:44:31 -05:00
child.forceDeath();
2019-04-21 01:30:03 -05:00
}
else {
child.destroy();
}
}
},
spawn: (key, json = {}) => {
if (!this.entity.is('listed')) {
return;
}
2019-04-21 14:57:35 -05:00
if (this.maxSpawns <= this.children.length) {
2019-04-21 01:30:03 -05:00
return;
}
const spawnJSON = this.spawnJSONs[key];
if (!spawnJSON) {
return;
}
const spawn = new Entity().fromJSON(merge(spawnJSON, json));
this.children.push(spawn);
2019-04-30 17:11:41 -05:00
spawn.once('destroy', () => {
2019-04-21 01:30:03 -05:00
const index = this.children.indexOf(spawn);
this.children.splice(index, 1);
})
const list = this.entity.list;
list.addEntity(spawn);
},
};
}
}