feat: spawner
This commit is contained in:
parent
c46109272a
commit
658a75bc3e
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@avocado/entity",
|
||||
"version": "1.0.9",
|
||||
"version": "1.0.10",
|
||||
"main": "index.js",
|
||||
"author": "cha0s",
|
||||
"license": "MIT",
|
||||
|
@ -15,6 +15,7 @@
|
|||
"debug": "^3.1.0",
|
||||
"immutable": "4.0.0-rc.12",
|
||||
"lodash.mapvalues": "4.6.0",
|
||||
"lodash.merge": "4.6.1",
|
||||
"lodash.without": "4.4.0"
|
||||
}
|
||||
}
|
||||
|
|
86
packages/entity/traits/spawner.trait.js
Normal file
86
packages/entity/traits/spawner.trait.js
Normal file
|
@ -0,0 +1,86 @@
|
|||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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')) {
|
||||
child.die();
|
||||
}
|
||||
else {
|
||||
child.destroy();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
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().fromJSON(merge(spawnJSON, json));
|
||||
this.children.push(spawn);
|
||||
spawn.on('destroy', () => {
|
||||
const index = this.children.indexOf(spawn);
|
||||
this.children.splice(index, 1);
|
||||
})
|
||||
const list = this.entity.list;
|
||||
list.addEntity(spawn);
|
||||
},
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user