2020-01-17 21:11:15 +01:00
|
|
|
/**
|
|
|
|
* KeyControls class
|
|
|
|
*/
|
2019-08-20 17:59:26 +02:00
|
|
|
class KeyControls {
|
2020-01-17 21:11:15 +01:00
|
|
|
/**
|
|
|
|
* Listens for keypresses and prevents default actions
|
|
|
|
*/
|
2019-08-20 17:59:26 +02:00
|
|
|
constructor() {
|
|
|
|
this.keys = {};
|
|
|
|
// Bind event handlers
|
|
|
|
document.addEventListener("keydown", e => {
|
2020-01-17 21:11:15 +01:00
|
|
|
if ([37, 38, 39, 40].indexOf(e.which) >= 0) {
|
2019-08-20 17:59:26 +02:00
|
|
|
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
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns value of action key (spacebar)
|
|
|
|
* @returns {boolean} Key value
|
|
|
|
*/
|
2019-08-20 17:59:26 +02:00
|
|
|
get action() {
|
|
|
|
// Spacebar
|
|
|
|
return this.keys[32];
|
|
|
|
}
|
|
|
|
|
2020-01-17 21:11:15 +01:00
|
|
|
/**
|
|
|
|
* Returns -1 on Arrow Left or A
|
|
|
|
*
|
|
|
|
* Returns 1 on Arrow Right or D
|
|
|
|
* @returns {number} Key Value
|
|
|
|
*/
|
|
|
|
get x() {
|
2019-08-20 17:59:26 +02:00
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
|
2020-01-17 21:11:15 +01:00
|
|
|
/**
|
|
|
|
* Returns -1 on Arrow Up or W
|
|
|
|
*
|
|
|
|
* Returns 1 on Arrow Down or S
|
|
|
|
* @returns {number} Key value
|
|
|
|
*/
|
|
|
|
get y() {
|
2019-08-20 17:59:26 +02:00
|
|
|
// 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-01-17 21:11:15 +01:00
|
|
|
/**
|
|
|
|
* Read or write value of any key
|
|
|
|
* @param {number} key Keycode for targetted key
|
|
|
|
* @param {*} [value] Value to set to key
|
|
|
|
* @return {*} Value of key
|
|
|
|
*/
|
2019-08-20 17:59:26 +02:00
|
|
|
key(key, value) {
|
|
|
|
if (value !== undefined) {
|
|
|
|
this.keys[key] = value;
|
|
|
|
}
|
|
|
|
return this.keys[key];
|
|
|
|
}
|
|
|
|
|
2020-01-17 21:11:15 +01:00
|
|
|
/**
|
|
|
|
* Resets default value to all keys
|
|
|
|
*/
|
2019-08-20 17:59:26 +02:00
|
|
|
reset() {
|
|
|
|
for (let key in this.keys) {
|
|
|
|
this.keys[key] = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
export default KeyControls;
|