-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectionInput.js
More file actions
39 lines (33 loc) · 889 Bytes
/
Copy pathDirectionInput.js
File metadata and controls
39 lines (33 loc) · 889 Bytes
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
class DirectionInput {
constructor() {
this.heldDirections = [];
this.map = {
"KeyW":"up",
"KeyS":"down",
"KeyA":"left",
"KeyD":"right",
"ArrowUp":"up",
"ArrowDown":"down",
"ArrowLeft":"left",
"ArrowRight":"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);
}
})
}
}