feat: custom death condition and actions

This commit is contained in:
cha0s 2019-04-19 17:23:40 -05:00
parent c9b51d81d9
commit 9463625d4f

View File

@ -1,3 +1,4 @@
import {behaviorItemFromJSON, createContext} from '@avocado/behavior';
import {compose} from '@avocado/core';
import {StateProperty, Trait} from '@avocado/entity';
@ -12,6 +13,70 @@ const decorate = compose(
export class Alive extends decorate(Trait) {
static defaultParams() {
return {
deathActions: {
type: 'actions',
traversals: [
{
type: 'traversal',
steps: [
{
type: 'key',
key: 'entity',
},
{
type: 'key',
key: 'transition',
},
{
type: 'invoke',
args: [
{
type: 'literal',
value: {
opacity: 0,
visibleScaleX: .3,
visibleScaleY: 3,
},
},
{
type: 'literal',
value: 0.2,
},
],
},
],
},
],
},
// By default, die when life <= 0.
deathCondition: {
type: 'condition',
operator: '<=',
operands: [
{
type: 'traversal',
steps: [
{
type: 'key',
key: 'entity',
},
{
type: 'key',
key: 'life',
},
],
},
{
type: 'literal',
value: 0,
},
],
},
};
}
static defaultState() {
return {
life: 100,
@ -19,6 +84,16 @@ export class Alive extends decorate(Trait) {
};
}
initialize() {
this._context = createContext();
this._context.add('entity', this.entity);
const actionsJSON = this.params.get('deathActions').toJS();
this._deathActions = behaviorItemFromJSON(actionsJSON);
const conditionJSON = this.params.get('deathCondition').toJS();
this._deathCondition = behaviorItemFromJSON(conditionJSON);
this._isDying = false;
}
listeners() {
return {
@ -34,21 +109,28 @@ export class Alive extends decorate(Trait) {
}
}
tick(elapsed) {
// ded
// @todo Custom death conditions.
if (this.entity.life <= 0) {
const allowDeath = this.entity.invokeHookFlat('allowDeath');
const overrides = allowDeath.filter((response) => {
return false === response;
});
// Something saved the day.
if (overrides.length > 0) {
methods() {
return {
}
else {
die: () => {
this._isDying = true;
this.entity.emit('dying');
this._deathActions.on('actionsFinished', () => {
this.entity.destroy();
});
},
};
}
tick(elapsed) {
if (this._isDying) {
this._deathActions.tick(this._context, elapsed);
}
else {
if (this._deathCondition.check(this._context)) {
// It's a good day to die.
this.entity.destroy();
this.entity.die();
}
}
}