avocado-old/packages/behavior/traits/behaved.trait.js

58 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-04-09 09:42:40 -05:00
import {compose} from '@avocado/core';
import {createContext, Routines} from '@avocado/behavior';
2019-04-14 20:21:52 -05:00
import {StateProperty, Trait} from '@avocado/entity';
2019-04-09 09:42:40 -05:00
const decorate = compose(
StateProperty('isBehaving'),
StateProperty('currentRoutine'),
);
export class Behaved extends decorate(Trait) {
static defaultParams() {
return {
routines: {},
};
}
static defaultState() {
return {
isBehaving: true,
currentRoutine: 'initial',
}
}
initialize() {
this._context = createContext();
this._context.add('entity', this.entity);
const routinesJSON = {
type: 'routines',
routines: this.params.get('routines').toJS(),
};
this._routines = (new Routines()).fromJSON(routinesJSON);
this._routines.context = this._context;
}
get context() {
return this._context;
}
listeners() {
return {
dying: () => {
this.entity.isBehaving = false;
},
};
}
tick(elapsed) {
const routine = this._routines.routine(this.entity.currentRoutine);
if (routine) {
routine.tick(elapsed);
}
}
2019-04-09 09:42:40 -05:00
}