-
Notifications
You must be signed in to change notification settings - Fork 0
/
controllerClient.js
62 lines (43 loc) · 1.35 KB
/
controllerClient.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
const { MultiKey, GamePad } = require('hud-gamepad');
const url = `ws://${document.location.hostname}:${document.location.port}`;
const socket = new WebSocket(url);
function reloadPage() {
setTimeout(() => document.location.reload(), 1000);
}
function showMessage(text) {
document.getElementById('message').innerHTML = text;
}
showMessage(`Connecting to: ${url}`);
socket.addEventListener('close', () => reloadPage());
window.addEventListener("orientationchange", () => reloadPage());
socket.addEventListener('open', event => showMessage(`Connected.`));
socket.addEventListener('message', event => showMessage(event.data));
GamePad.setup({
debug: false,
trace: false,
start: true,
joystick: false,
hint: true,
buttons: [
{ name: "right", "key": "d" },
{ name: "down", "key": "s" },
{ name: "up", "key": "w" },
{ name: "left", "key": "a" },
]
});
MultiKey.setup(GamePad.events, "wsad ", true);
let state = JSON.stringify(GamePad.observe());
function loop() {
const newState = JSON.stringify(GamePad.observe());
if (state !== newState) {
socket.send(newState);
};
state = newState;
window.requestAnimationFrame(loop);
}
document.addEventListener('keydown', event => {
if (event.key === ' ') {
socket.send(JSON.stringify({ start: 1 }));
}
});
loop();