humus-old/common/traits/controllable.trait.js
2019-10-11 02:17:07 -05:00

66 lines
1.7 KiB
JavaScript

import {TickingPromise} from '@avocado/core';
import {Trait} from '@avocado/entity';
import {Vector} from '@avocado/math';
// Input handling.
export class Controllable extends Trait {
static type() {
return 'controllable';
}
constructor(entity, params, state) {
super(entity, params, state);
this._itemPromise = undefined;
this._movementVector = [0, 0];
}
set inputStream(inputStream) {
for (let i = 0; i < inputStream.length; i++) {
const {action, value} = inputStream[i];
const normalized = 0 === value ? -1 : 1;
switch (action) {
case 'MoveUp':
this._movementVector[1] -= normalized;
break;
case 'MoveRight':
this._movementVector[0] += normalized;
break;
case 'MoveDown':
this._movementVector[1] += normalized;
break;
case 'MoveLeft':
this._movementVector[0] -= normalized;
break;
case 'UseItem':
if (AVOCADO_SERVER) {
if (-1 !== value && !this._itemPromise) {
this._itemPromise = this.entity.useItemInSlot(value);
Promise.resolve(this._itemPromise).then(() => {
this._itemPromise = undefined;
});
}
}
break;
}
}
if (Vector.isZero(this._movementVector)) {
this.entity.currentAnimation = 'idle';
}
else {
this.entity.currentAnimation = 'moving';
}
}
tick(elapsed) {
if (this._itemPromise && this._itemPromise instanceof TickingPromise) {
this._itemPromise.tick(elapsed);
}
if (!Vector.isZero(this._movementVector)) {
this.entity.requestMovement(this._movementVector);
}
}
}