-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyHandler.js
73 lines (65 loc) · 2.09 KB
/
KeyHandler.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class KeyHandler {
constructor(gameLoop) {
this.keyPressed = [];
let handler = this;
document.addEventListener('keydown', function(e) {
handler.keydown(e, handler);
}, false);
document.addEventListener('keyup', function(e) {
handler.keyup(e, handler);
}, false);
this.checkLoop = gameLoop.add(function() {
for (let checkKey in handler.continuousKeyFunctions)
handler.isPressed(checkKey) && handler.continuousKeyFunctions[checkKey].action(handler.keyPressed[handler.keyPressed.map(k => k.key).indexOf(checkKey)].event);
});
this.singleKeyFunctions = {};
this.continuousKeyFunctions = {};
}
get keyMap() {
let map = {};
map.continuous = {};
for (let key in this.continuousKeyFunctions)
map.continuous[key] = this.continuousKeyFunctions[key];
map.single = {};
for (let key in this.singleKeyFunctions)
map.single[key] = this.singleKeyFunctions[key];
return map;
}
setSingleKey(key, name, fun) {
this.singleKeyFunctions[key] = {
action: fun,
name: name
};
}
deleteSingleKey(key) {
delete this.singleKeyFunctions[key];
}
setContinuousKey(key, name, fun) {
this.continuousKeyFunctions[key] = {
action: fun,
name: name
};
}
deleteContinuousKey(key) {
delete this.continuousKeyFunctions[key];
}
keydown(e, handler) {
let key = e.key;
if (!handler.isPressed(key)) {
handler.keyPressed.push({
key: key,
event: e
});
}
for (let checkKey in handler.singleKeyFunctions)
if (key === checkKey)
handler.singleKeyFunctions[checkKey].action(e);
}
keyup(e, handler) {
let key = e.key;
handler.keyPressed.splice(handler.keyPressed.map(k => k.key).indexOf(key), 1);
}
isPressed(key) {
return this.keyPressed.map(k => k.key).includes(key);
}
}