-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectionInput.js
37 lines (33 loc) · 934 Bytes
/
DirectionInput.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
class DirectionInput{
constructor(config) {
this.heldDirection = []
this.map = {
"ArrowUp": "up",
"ArrowDown": "down",
"ArrowLeft": "left",
"ArrowRight": "right",
"KeyW": "up",
"KeyS": "down",
"KeyA": "left",
"KeyD": "right",
}
}
get direction(){
return this.heldDirection[0];
}
init(){
document.addEventListener("keydown", e => {
const dir = this.map[e.code]
if(dir && this.heldDirection.indexOf(dir) === -1){
this.heldDirection.unshift(dir);
}
});
document.addEventListener("keyup", e => {
const dir = this.map[e.code];
const index = this.heldDirection.indexOf(dir);
if(index > -1){
this.heldDirection.splice(index, 1);
}
})
}
}