-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyListener.ts
More file actions
47 lines (35 loc) · 1.31 KB
/
KeyListener.ts
File metadata and controls
47 lines (35 loc) · 1.31 KB
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
type KeyState = {
value: boolean;
ifKeydown: Function;
}
class KeyStates {
public keyStateMap: Map<string, KeyState>;
constructor() {
this.keyStateMap = new Map<string, KeyState>();
}
initKeyStates(keys: {name: string, ifDown: Function}[]) {
console.log(this.keyStateMap);
for(const key of keys) {
this.keyStateMap.set(key.name, {value: false, ifKeydown: key.ifDown});
}
console.log(this.keyStateMap);
}
static onKeydown(ev: KeyboardEvent, keyStateMap) {
if (!keyStateMap.keyStateMap.has(ev.code)) {return;}
let keyFunction = keyStateMap.keyStateMap.get(ev.code).ifKeydown;
keyStateMap.keyStateMap.set(ev.code, {value: true, ifKeydown: keyFunction});
}
static onKeyup(ev: KeyboardEvent, keyStateMap) {
if (!keyStateMap.keyStateMap.has(ev.code)) {return;}
let keyFunction = keyStateMap.keyStateMap.get(ev.code).ifKeydown;
keyStateMap.keyStateMap.set(ev.code, {value: false, ifKeydown: keyFunction});
}
static callFunctions(keyStateMap) {
let callerFunction = function(value: KeyState, key: string, map: Map<string, KeyState>) {
if (value.value) {
value.ifKeydown();
}
}
keyStateMap.keyStateMap.forEach(callerFunction);
}
}