-
Notifications
You must be signed in to change notification settings - Fork 0
/
controls.js
48 lines (43 loc) · 971 Bytes
/
controls.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
const controlMappings = [
{
w: "up",
s: "down",
" ": "start",
},
{
ArrowUp: "up",
ArrowDown: "down",
Enter: "start",
},
];
const controls = [{}, {}];
document.addEventListener("keydown", (evt) => {
controls.forEach((control, i) => {
control[controlMappings[i][evt.key]] = true;
});
});
document.addEventListener("keyup", (evt) => {
controls.forEach((control, i) => {
control[controlMappings[i][evt.key]] = false;
});
});
function getGamePadControl(index) {
const gamepad = navigator.getGamepads()[index];
if (gamepad) {
const axes = gamepad.axes;
return {
start: gamepad.buttons[4].pressed,
up: axes[0] > 0.2,
down: axes[1] > 0.2,
};
}
}
function getKeyBoardControl(index) {
return Object.assign({}, controls[index]);
}
export default function getControls() {
return [
getGamePadControl(0) || getKeyBoardControl(0),
getGamePadControl(1) || getKeyBoardControl(1),
];
}