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

81 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-04-09 09:42:40 -05:00
import {compose} from '@avocado/core';
2019-04-14 20:21:52 -05:00
import {StateProperty, Trait} from '@avocado/entity';
2019-04-09 09:42:40 -05:00
import {createContext} from '../context';
import {Routines} from '../item/routines';
2019-04-09 09:42:40 -05:00
const decorate = compose(
StateProperty('currentRoutine'),
);
export class Behaved extends decorate(Trait) {
static defaultParams() {
return {
routines: {},
};
}
static defaultState() {
return {
currentRoutine: 'initial',
}
}
2019-05-05 04:26:35 -05:00
static type() {
return 'behaved';
}
2019-04-09 09:42:40 -05:00
initialize() {
this._context = createContext();
this._context.add('entity', this.entity);
this._currentRoutine = undefined;
2019-04-19 15:51:50 -05:00
this._isBehaving = true;
2019-05-04 14:06:47 -05:00
const routinesJSON = this.params.routines;
2019-04-09 09:42:40 -05:00
this._routines = (new Routines()).fromJSON(routinesJSON);
this._routines.context = this._context;
this.updateCurrentRoutine();
2019-04-09 09:42:40 -05:00
}
2019-04-30 17:11:41 -05:00
destroy() {
this._context.clear();
this._currentRoutine = undefined;
this._routines = undefined;
}
2019-04-09 09:42:40 -05:00
get context() {
return this._context;
}
2019-04-19 15:51:50 -05:00
set isBehaving(isBehaving) {
this._isBehaving = isBehaving;
}
updateCurrentRoutine() {
this._currentRoutine = this._routines.routine(
this.entity.currentRoutine
);
}
2019-04-09 09:42:40 -05:00
listeners() {
return {
currentRoutineChanged: () => {
this.updateCurrentRoutine();
},
2019-04-09 09:42:40 -05:00
dying: () => {
2019-04-19 15:51:50 -05:00
this._isBehaving = false;
2019-04-09 09:42:40 -05:00
},
};
}
tick(elapsed) {
2019-04-19 15:51:50 -05:00
if (this._currentRoutine && this._isBehaving) {
this._currentRoutine.tick(elapsed);
}
}
2019-04-09 09:42:40 -05:00
}