humus-old/common/traits/controllable.trait.js

69 lines
1.7 KiB
JavaScript

import * as I from 'immutable';
import {TickingPromise} from '@avocado/core';
import {Trait} from '@avocado/entity';
// Input handling.
export class Controllable extends Trait {
static type() {
return 'controllable';
}
constructor(entity, params, state) {
super(entity, params, state);
this._inputState = I.Map();
this._itemPromise = undefined;
}
set inputState(inputState) {
this._inputState = I.Map(inputState);
if (AVOCADO_SERVER) {
if (inputState.has('UseItem')) {
const slotIndex = inputState.get('UseItem');
this._itemPromise = this.entity.useItemInSlot(slotIndex);
Promise.resolve(this._itemPromise).then(() => {
this._itemPromise = undefined;
});
}
}
}
tick(elapsed) {
if (this._itemPromise && this._itemPromise instanceof TickingPromise) {
this._itemPromise.tick(elapsed);
}
const {_inputState: inputState} = this;
if (0 === inputState.size) {
this.entity.currentAnimation = 'idle';
return;
}
const movementVector = [0, 0];
if (inputState.has('MoveToX')) {
movementVector[0] = inputState.get('MoveToX') / 127;
}
if (inputState.has('MoveToY')) {
movementVector[1] = inputState.get('MoveToY') / 127;
}
if (inputState.has('MoveUp')) {
movementVector[1] -= 1;
}
if (inputState.has('MoveRight')) {
movementVector[0] += 1;
}
if (inputState.has('MoveDown')) {
movementVector[1] += 1;
}
if (inputState.has('MoveLeft')) {
movementVector[0] -= 1;
}
if (0 === movementVector[0] && 0 === movementVector[1]) {
return;
}
this.entity.requestMovement(movementVector);
this.entity.currentAnimation = 'moving';
}
}