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

87 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-04-21 01:30:03 -05:00
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,
};
}
2019-05-05 04:26:35 -05:00
static type() {
return 'spawner';
}
destroy() {
this.children = [];
}
constructor(entity, params, state) {
super(entity, params, state);
2019-04-21 01:30:03 -05:00
this.children = [];
2019-05-04 14:06:47 -05:00
this.spawnJSONs = this.params.spawns;
2019-04-21 01:30:03 -05:00
}
listeners() {
return {
dying: () => {
this.isSpawning = false;
},
};
}
methods() {
return {
killAllChildren: () => {
for (let i = 0; i < this.children.length; i++) {
this.children[i].destroyGently();
2019-04-21 01:30:03 -05:00
}
},
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;
}
2019-05-17 04:35:10 -05:00
const spawn = new Entity(spawnJSON, json);
2019-04-21 01:30:03 -05:00
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);
},
};
}
}