-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.js
81 lines (74 loc) · 2.38 KB
/
input.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
74
75
76
77
78
79
80
81
// by default set direction and last direction nowhere
let inputDir = { x: 0, y: 0 }
let lastInputDir = { x: 0, y: 0 }
export function getInputDir() {
lastInputDir = inputDir
return inputDir
}
let up = document.getElementById('up');
let down = document.getElementById('down');
let left = document.getElementById('left');
let right = document.getElementById('right');
// executes function when user presses up / down / left / right button on screen
up.addEventListener("click", function() {
// cannot select up if direction is going down
if (lastInputDir.y !== 0) {
return;
}
// y: -1 moves up
inputDir = { x: 0, y: -1 }
});
down.addEventListener("click", function() {
// cannot select down if direction is going up
if (lastInputDir.y !== 0) {
return;
}
// y: 1 moves down
inputDir = { x: 0, y: 1 }
});
left.addEventListener("click", function() {
// cannot select left if direction is going right
if (lastInputDir.x !== 0) {
return;
}
// x: -1 moves left
inputDir = { x: -1, y: 0 }
});
right.addEventListener("click", function() {
// cannot select right if direction is going left
if (lastInputDir.x !== 0) {
return;
}
// x: 1 moves right
inputDir = { x: 1, y: 0 }
});
window.addEventListener('keydown', e => {
// e.key is key up, key down, key left or key right
switch (e.key) {
case 'ArrowUp':
// if moving up or down at present ignore line 60
// cannot select up if direction is going down
if (lastInputDir.y !== 0) break
// y: -1 moves up
inputDir = { x: 0, y: -1 }
break
case 'ArrowDown':
// if moving up or down at present ignore line 66
if (lastInputDir.y !== 0) break
// y: 1 moves down
inputDir = { x: 0, y: 1 }
break
case 'ArrowLeft':
// if moving left or right at present ignore line 72
if (lastInputDir.x !== 0) break
// x: -1 moves left
inputDir = { x: -1, y: 0 }
break
case 'ArrowRight':
// if moving left or right at present ignore line 78
if (lastInputDir.x !== 0) break
// x: 1 moves right
inputDir = { x: 1, y: 0 }
break
}
})