UNPKG

@wonderlandengine/components

Version:

Wonderland Engine's official component library.

90 lines 3.27 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { vec3 } from 'gl-matrix'; import { Component } from '@wonderlandengine/api'; import { property } from '@wonderlandengine/api/decorators.js'; const _direction = new Float32Array(3); const _tempDualQuat = new Float32Array(8); /** * Basic movement with W/A/S/D keys. */ class WasdControlsComponent extends Component { static TypeName = 'wasd-controls'; /** Movement speed in m/s. */ speed; /** Flag for only moving the object on the global x & z planes */ lockY; /** Object of which the orientation is used to determine forward direction */ headObject; right = false; down = false; left = false; up = false; start() { this.headObject = this.headObject || this.object; } onActivate() { window.addEventListener('keydown', this.press); window.addEventListener('keyup', this.release); } onDeactivate() { window.removeEventListener('keydown', this.press); window.removeEventListener('keyup', this.release); } update() { vec3.zero(_direction); if (this.up) _direction[2] -= 1.0; if (this.down) _direction[2] += 1.0; if (this.left) _direction[0] -= 1.0; if (this.right) _direction[0] += 1.0; vec3.normalize(_direction, _direction); _direction[0] *= this.speed; _direction[2] *= this.speed; vec3.transformQuat(_direction, _direction, this.headObject.getTransformWorld(_tempDualQuat)); if (this.lockY) { _direction[1] = 0; vec3.normalize(_direction, _direction); vec3.scale(_direction, _direction, this.speed); } this.object.translateLocal(_direction); } press = (e) => { this.handleKey(e, true); }; release = (e) => { this.handleKey(e, false); }; handleKey(e, b) { if (e.code === 'ArrowUp' || e.code === 'KeyW' || e.code === 'KeyZ') { this.up = b; } else if (e.code === 'ArrowRight' || e.code === 'KeyD') { this.right = b; } else if (e.code === 'ArrowDown' || e.code === 'KeyS') { this.down = b; } else if (e.code === 'ArrowLeft' || e.code === 'KeyA' || e.code === 'KeyQ') { this.left = b; } } } __decorate([ property.float(0.1) ], WasdControlsComponent.prototype, "speed", void 0); __decorate([ property.bool(false) ], WasdControlsComponent.prototype, "lockY", void 0); __decorate([ property.object() ], WasdControlsComponent.prototype, "headObject", void 0); export { WasdControlsComponent }; //# sourceMappingURL=wasd-controls.js.map