-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.js
96 lines (87 loc) · 2.11 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const deadZone = 0.02;
export function initializeInput() {
const arrowKeys = {
up: false,
down: false,
left: false,
right: false,
};
const handlers = {
fireListeners: [],
jumpListeners: [],
};
document.onkeydown = (e) => {
switch (e.key) {
case "ArrowUp":
arrowKeys.up = true;
break;
case "ArrowDown":
arrowKeys.down = true;
break;
case "ArrowLeft":
arrowKeys.left = true;
break;
case "ArrowRight":
arrowKeys.right = true;
break;
case "f":
handlers.fireListeners.forEach((handler) => handler());
break;
case " ":
handlers.jumpListeners.forEach((handler) => handler());
break;
}
};
document.onkeyup = (e) => {
switch (e.code) {
case "ArrowUp":
arrowKeys.up = false;
break;
case "ArrowDown":
arrowKeys.down = false;
break;
case "ArrowLeft":
arrowKeys.left = false;
break;
case "ArrowRight":
arrowKeys.right = false;
break;
}
};
let direction = { x: 0.0, y: 0.0, z: 0.0 };
return {
applyFrame() {
let xInputRatio = 0;
let zInputRatio = 0;
const gamepads = navigator.getGamepads();
if (gamepads && gamepads.length > 0 && gamepads[0]) {
xInputRatio = gamepads[0].axes[0];
zInputRatio = gamepads[0].axes[1];
}
if (arrowKeys.down === true) {
zInputRatio = 1;
} else if (arrowKeys.up === true) {
zInputRatio = -1;
}
if (arrowKeys.right === true) {
xInputRatio = 1;
} else if (arrowKeys.left === true) {
xInputRatio = -1;
}
direction = {
x: Math.abs(xInputRatio) > deadZone ? xInputRatio : 0.0,
y: 0.0,
z: Math.abs(zInputRatio) > deadZone ? zInputRatio : 0.0,
};
},
get direction() {
return direction;
},
registerFireListener(fireListener) {
handlers.fireListeners.push(fireListener);
},
registerJumpListener(jumpListener) {
handlers.jumpListeners.push(jumpListener);
},
};
}