asdf-games/lib/controls/KeyControls.js
Arne van Iterson 9da289ea62 Added listen variable to controls
This makes it possible to send controls over socket.io
2020-04-23 22:30:06 +02:00

80 lines
1.2 KiB
JavaScript

class KeyControls {
constructor(listen = true) {
this.keys = {};
if (listen) {
// 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];
}
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;
}
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;
}
}
}
module.exports = KeyControls;