asdf-games/lib/controls/KeyControls.js

78 lines
1.2 KiB
JavaScript
Raw Normal View History

class KeyControls {
2020-02-20 08:40:50 +01:00
constructor() {
this.keys = {};
// Bind event handlers
document.addEventListener("keydown", e => {
if ([37, 38, 39, 40].indexOf(e.which) >= 0) {
e.preventDefault();
}
this.keys[e.which] = true;
}, false);
document.addEventListener("keyup", e => {
this.keys[e.which] = false;
}, false);
}
get action() {
// Spacebar
return this.keys[32];
}
2020-03-29 18:39:23 +02:00
get ctrl() {
// Control
return this.keys[17];
}
get shift() {
// Shift
return this.keys[16];
}
get escape() {
// Escape
return this.keys[27];
}
get x() {
// Arrow Left or A (WASD)
if (this.keys[37] || this.keys[65]) {
return -1;
}
// Arrow Right or D (WASD)
if (this.keys[39] || this.keys[68]) {
return 1;
}
return 0;
}
get y() {
// Arrow Up or W (WASD)
if (this.keys[38] || this.keys[87]) {
return -1;
}
// Arrow Down or S (WASD)
if (this.keys[40] || this.keys[83]) {
return 1;
}
return 0;
}
2020-02-20 08:40:50 +01:00
key(key, value) {
if (value !== undefined) {
this.keys[key] = value;
}
return this.keys[key];
}
reset() {
for (let key in this.keys) {
this.keys[key] = false;
}
}
}
2020-02-29 13:45:56 +01:00
module.exports = KeyControls;