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