forked from ynoproject/forest-orb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gamecanvas.js
358 lines (320 loc) · 11.4 KB
/
gamecanvas.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
const preventNativeKeys = ['ArrowUp', 'ArrowDown', 'ArrowRight', 'ArrowLeft', ' ', 'F12'];
const keys = new Map();
const keysDown = new Map();
const canvas = document.getElementById('canvas');
const gameContainer = document.getElementById('gameContainer');
let lastTouchedId;
// Make EasyRPG player embeddable
canvas.addEventListener('mouseenter', () => canvas.focus());
canvas.addEventListener('click', () => canvas.focus());
// Handle clicking on the fullscreen button
document.querySelector('#controls-fullscreen').addEventListener('click', () => {
const layout = document.getElementById('layout');
if (layout.requestFullscreen) {
if (!document.fullscreenElement) {
layout.requestFullscreen();
setFullscreenControlsHideTimer();
} else
document.exitFullscreen();
} else if (layout.webkitRequestFullscreen) {
if (!document.webkitFullscreenElement) {
layout.webkitRequestFullscreen();
setFullscreenControlsHideTimer();
} else
document.webkitExitFullscreen();
}
onResize();
});
{
const layout = document.getElementById('layout');
if (!(layout.requestFullscreen || layout.webkitRequestFullscreen)) {
document.getElementById('controls-fullscreen').classList.add('hidden');
}
}
/**
* Simulate a keyboard event on the emscripten canvas
*
* @param {string} eventType Type of the keyboard event
* @param {string} key Key to simulate
* @param {number} keyCode Key code to simulate (deprecated)
*/
function simulateKeyboardEvent(eventType, key, keyCode) {
const event = new Event(eventType, { bubbles: true });
event.key = key;
event.code = key;
// Deprecated, but necessary for emscripten somehow
event.keyCode = keyCode;
event.which = keyCode;
canvas.dispatchEvent(event);
}
/**
* Simulate a keyboard input from `keydown` to `keyup`
*
* @param {string} key Key to simulate
* @param {number} keyCode Key code to simulate (deprecated)
*/
function simulateKeyboardInput(key, keyCode) {
simulateKeyboardEvent('keydown', key, keyCode);
window.setTimeout(() => {
simulateKeyboardEvent('keyup', key, keyCode);
}, 100);
}
/**
* Bind a node by a specific key to simulate on touch
*
* @param {*} node The node to bind a key to
* @param {string} key Key to simulate
* @param {number} keyCode Key code to simulate (deprecated)
*/
function bindKey(node, key, keyCode) {
keys.set(node.id, { key, keyCode });
node.addEventListener('touchstart', event => {
if (event.cancelable)
event.preventDefault();
simulateKeyboardEvent('keydown', key, keyCode);
keysDown.set(event.target.id, node.id);
node.classList.add('active');
});
node.addEventListener('touchend', event => {
if (event.cancelable)
event.preventDefault();
const pressedKey = keysDown.get(event.target.id);
if (pressedKey && keys.has(pressedKey)) {
const { key, keyCode } = keys.get(pressedKey);
simulateKeyboardEvent('keyup', key, keyCode);
}
keysDown.delete(event.target.id);
node.classList.remove('active');
if (lastTouchedId) {
document.getElementById(lastTouchedId).classList.remove('active');
}
});
// Inspired by https://github.com/pulsejet/mkxp-web/blob/262a2254b684567311c9f0e135ee29f6e8c3613e/extra/js/dpad.js
node.addEventListener('touchmove', event => {
const { target, clientX, clientY } = event.changedTouches[0];
const origTargetId = keysDown.get(target.id);
const nextTargetId = document.elementFromPoint(clientX, clientY).id;
if (origTargetId === nextTargetId) return;
if (origTargetId) {
const { key, keyCode } = keys.get(origTargetId);
simulateKeyboardEvent('keyup', key, keyCode);
keysDown.delete(target.id);
document.getElementById(origTargetId).classList.remove('active');
}
if (keys.has(nextTargetId)) {
const { key, keyCode } = keys.get(nextTargetId);
simulateKeyboardEvent('keydown', key, keyCode);
keysDown.set(target.id, nextTargetId);
lastTouchedId = nextTargetId;
document.getElementById(nextTargetId).classList.add('active');
}
})
}
/** @type {{[key: number]: Gamepad}} */
const gamepads = {};
const haveEvents = 'ongamepadconnected' in window;
function addGamepad(gamepad) {
if (gamepad == undefined)
return;
gamepads[gamepad.index] = gamepad;
updateTouchControlsVisibility();
}
function removeGamepad(gamepad) {
if (gamepad == undefined)
return;
delete gamepads[gamepad.index];
updateTouchControlsVisibility();
}
/** @returns {Gamepad[]} */
function getGamepads() {
return navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
}
function scanGamePads() {
const pads = getGamepads();
for (let i = 0; i < pads.length; i++) {
if (pads[i]) {
if (pads[i].index in gamepads)
gamepads[pads[i].index] = pads[i];
else
addGamepad(pads[i]);
}
}
}
if (!haveEvents) {
setInterval(scanGamePads, 500);
}
window.addEventListener('gamepadconnected', e => addGamepad(e.gamepad));
window.addEventListener('gamepaddisconnected', e => removeGamepad(e.gamepad));
function updateTouchControlsVisibility() {
if (hasTouchscreen && !Object.keys(gamepads).length) {
for (const elem of document.querySelectorAll('#dpad, #apad'))
elem.style.display = '';
} else {
// If we don't have a touch screen, OR any gamepads are connected...
for (const elem of document.querySelectorAll('#dpad, #apad'))
elem.style.display = 'none'; // Hide the touch controls
}
}
// Bind all elements providing a `data-key` attribute with the
// given key on touch-based devices
if (hasTouchscreen) {
for (const button of document.querySelectorAll('[data-key]'))
bindKey(button, button.dataset.key, button.dataset.keyCode);
// Setup for the floating controls
// These controls are only available in fullscreen mode.
/** @type {Touch} */
let anchor;
/** @type {Touch} */
let compass;
let lastDirection;
const directions = [
{ key: 'ArrowUp', code: 38, button: document.getElementById('joystickUp') },
{ key: 'ArrowRight', code: 39, button: document.getElementById('joystickRight') },
{ key: 'ArrowDown', code: 40, button: document.getElementById('joystickDown') },
{ key: 'ArrowLeft', code: 37, button: document.getElementById('joystickLeft') },
];
const joystick = document.getElementById('joystick');
/** @type {SVGCircleElement} */
const insetCircle = document.getElementById('insetCircle');
const joystickCircle = document.getElementById('joystickCircle');
const dpadCircle = document.getElementById('dpadCircle');
const extent = 10;
const deadzone = 0.5;
canvas.addEventListener('touchstart', ev => {
if (ev.targetTouches.length !== 1 || !document.fullscreenElement) return;
let radius;
switch (globalConfig.mobileControlsType) {
case 'joystick': radius = joystickCircle.getBoundingClientRect().width / 2; break;
case 'dpad': radius = dpadCircle.getBoundingClientRect().width / 2; break;
case 'default':
default:
return;
}
joystick.classList.remove('fadeOut');
anchor = ev.targetTouches[0];
joystick.style.top = `${anchor.screenY - radius}px`;
joystick.style.left = `${anchor.screenX - radius}px`;
requestAnimationFrame(function driveControls() {
let direction;
if (direction = directions[lastDirection])
simulateKeyboardEvent('keyup', direction.key, direction.code);
if (anchor && compass) {
let dx = compass.clientX - anchor.clientX;
let dy = compass.clientY - anchor.clientY;
const angle = Math.atan2(dy, dx);
let deg = angle * (180 / Math.PI);
// 90 degrees to counteract the top-left origin
deg = (deg + 360 + 90) % 360;
if (deg >= 315 || deg < 45) {
lastDirection = 0;
} else if (deg >= 45 && deg < 135) {
lastDirection = 1;
} else if (deg >= 135 && deg < 225) {
lastDirection = 2;
} else if (deg >= 225 && deg < 315) {
lastDirection = 3;
}
if ((Math.abs(dx) >= deadzone || Math.abs(dy) >= deadzone) && (direction = directions[lastDirection])) {
simulateKeyboardEvent('keydown', direction.key, direction.code);
// Process visual changes for the controls
switch (globalConfig.mobileControlsType) {
case 'dpad':
for (const { button } of Object.values(directions))
button.classList.remove('active');
direction.button.classList.add('active');
break;
case 'joystick': {
dx = Math.max(Math.min(dx, extent), -extent);
dy = Math.max(Math.min(dy, extent), -extent);
const magnitude = Math.sqrt(dx * dx + dy * dy);
if (magnitude > extent) {
const scale = extent / magnitude;
dx *= scale;
dy *= scale;
}
insetCircle.setAttribute('cx', 25 + dx);
insetCircle.setAttribute('cy', 25 + dy);
break;
}
}
}
} else if (!anchor) return;
requestAnimationFrame(driveControls);
});
});
canvas.addEventListener('touchmove', ev => {
if (!anchor && ev.targetTouches.length) {
anchor = ev.targetTouches[0];
return;
}
compass = ev.targetTouches[0];
});
canvas.addEventListener('touchend', () => {
anchor = compass = undefined;
joystick.classList.add('fadeOut');
switch (globalConfig.mobileControlsType) {
case 'joystick':
insetCircle.setAttribute('cx', 25);
insetCircle.setAttribute('cy', 25);
break;
case 'dpad':
for (const { button } of Object.values(directions))
button.classList.remove('active');
break;
}
});
} else {
// Prevent scrolling when pressing specific keys
canvas.addEventListener('keydown', event => {
if (preventNativeKeys.includes(event.key))
event.preventDefault();
else if (globalConfig.tabToChat && event.key === 'Tab') {
event.preventDefault();
const chatInput = document.getElementById('chatInput');
let input;
if (chatInput.offsetWidth)
input = chatInput;
else {
const nameInput = document.getElementById('nameInput');
if (nameInput.offsetWidth)
input = nameInput;
}
if (input)
window.setTimeout(() => input.focus(), 0);
} else {
const keyLc = event.key.toLowerCase();
if (globalConfig.gameChat && (keyLc === 't' || keyLc === 'm'
|| (keyLc === 'g' && globalConfig.gameChatGlobal)
|| (keyLc === 'p' && globalConfig.gameChatParty && joinedPartyId))) {
const gameChatInput = document.getElementById('gameChatInput');
switch (keyLc) {
case 'm':
setGameChatMode(0);
break;
case 'g':
setGameChatMode(1);
break;
case 'p':
setGameChatMode(2);
break;
}
setTimeout(() => {
gameChatInput.onfocus();
gameChatInput.focus();
}, 0);
}
}
});
const onTabInput = event => {
if (globalConfig.tabToChat && event.key === 'Tab') {
event.preventDefault();
canvas.focus();
}
};
document.getElementById('chatInput').addEventListener('keydown', onTabInput);
document.getElementById('nameInput').addEventListener('keydown', onTabInput);
canvas.addEventListener('contextmenu', event => {
event.preventDefault();
});
}
updateTouchControlsVisibility();