humus-old/common/traits/lootable.trait.js
2019-11-03 14:57:34 -06:00

82 lines
1.7 KiB
JavaScript

import {compose, Property} from '@avocado/core';
import {StateProperty, Trait, Entity} from '@avocado/entity';
import {randomNumber, Rectangle, Vector} from '@avocado/math';
const decorate = compose(
StateProperty('lootable', {
track: true,
}),
);
export class Lootable extends decorate(Trait) {
static defaultParams() {
return {
table: [],
};
}
static defaultState() {
return {
lootable: true,
};
}
static type() {
return 'lootable';
}
constructor(entity, params, state) {
super(entity, params, state);
}
calculateLoot() {
const jsons = [];
const roll = Math.random() * 100;
for (const {perc, json} of this.params.table) {
if (perc > roll) {
jsons.push(json);
}
}
return jsons;
}
hooks() {
const hooks = {};
if (AVOCADO_SERVER) {
hooks['died'] = () => {
const jsons = this.calculateLoot();
const position = this.entity.position;
const promises = [];
for (let i = 0; i < jsons.length; i++) {
const json = jsons[i];
if (!json.traits) {
json.traits = {};
}
json.traits.emitted = {
params: {
force: [0, 8],
velocity: [
randomNumber(-0.5, 0.5),
randomNumber(-1.25, -0.75)
],
position,
transient: false,
ttl: 0.25,
},
};
const promise = this.entity.emitParticleJson(
json
).then((particle) => {
this.entity.list.addEntity(particle);
});
promises.push(promise);
}
return Promise.all(promises);
};
}
return hooks;
}
}