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

89 lines
1.6 KiB
JavaScript

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,
};
}
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 spawn = new Entity(merge(spawnJSON, json));
this.children.push(spawn);
spawn.once('destroy', () => {
const index = this.children.indexOf(spawn);
this.children.splice(index, 1);
})
const list = this.entity.list;
list.addEntity(spawn);
},
};
}
}