2019-08-20 17:59:26 +02:00
|
|
|
class KeyControls {
|
2020-02-20 08:40:50 +01:00
|
|
|
|
2020-03-21 17:22:28 +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);
|
|
|
|
}
|
2020-01-17 21:11:15 +01:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
get action() {
|
|
|
|
// Spacebar
|
|
|
|
return this.keys[32];
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
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];
|
|
|
|
}
|
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
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;
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
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;
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-02-20 08:40:50 +01:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
key(key, value) {
|
|
|
|
if (value !== undefined) {
|
|
|
|
this.keys[key] = value;
|
|
|
|
}
|
|
|
|
return this.keys[key];
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
2020-03-21 17:22:28 +01:00
|
|
|
reset() {
|
|
|
|
for (let key in this.keys) {
|
|
|
|
this.keys[key] = false;
|
|
|
|
}
|
|
|
|
}
|
2019-08-20 17:59:26 +02:00
|
|
|
|
|
|
|
}
|
2020-02-29 13:45:56 +01:00
|
|
|
|
|
|
|
module.exports = KeyControls;
|