File size: 943 Bytes
d0a5946 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** Keyboard driving input (WASD / arrows). */
export class DriveControls {
constructor(target = window) {
this.keys = new Set();
this._down = (e) => this.keys.add(e.code);
this._up = (e) => this.keys.delete(e.code);
target.addEventListener('keydown', this._down);
target.addEventListener('keyup', this._up);
}
dispose(target = window) {
target.removeEventListener('keydown', this._down);
target.removeEventListener('keyup', this._up);
}
sample() {
const forward = this.keys.has('KeyW') || this.keys.has('ArrowUp');
const back = this.keys.has('KeyS') || this.keys.has('ArrowDown');
const left = this.keys.has('KeyA') || this.keys.has('ArrowLeft');
const right = this.keys.has('KeyD') || this.keys.has('ArrowRight');
return {
throttle: (forward ? 1 : 0) - (back ? 1 : 0),
steer: (left ? 1 : 0) - (right ? 1 : 0),
brake: this.keys.has('Space') ? 1 : 0,
};
}
}
|