-
Notifications
You must be signed in to change notification settings - Fork 66
/
controller.js
79 lines (60 loc) · 1.82 KB
/
controller.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
// https://github.com/torch2424/responsive-gamepad
import { ResponsiveGamepad } from 'responsive-gamepad';
import ResponsiveGamepadPluginGB from './gbplugin';
import { WORKER_MESSAGE_TYPE } from '../worker/constants';
import { getEventData } from '../worker/util';
class WasmBoyControllerService {
constructor() {
// Our wasm instance
this.worker = undefined;
this.isEnabled = false;
// Bind Repsonsive Gamepad to this
this.ResponsiveGamepad = ResponsiveGamepad;
ResponsiveGamepad.addPlugin(ResponsiveGamepadPluginGB());
}
initialize() {
if (!this.isEnabled) {
this.enableDefaultJoypad();
}
return Promise.resolve();
}
setWorker(worker) {
this.worker = worker;
}
updateController() {
if (!this.isEnabled) {
return {};
}
// Create an abstracted controller state
const controllerState = ResponsiveGamepad.getState();
// Set the new controller state on the instance
this.setJoypadState(controllerState);
// Return the controller state in case we need something from it
return controllerState;
}
setJoypadState(controllerState) {
const setJoypadStateParamsAsArray = [
controllerState.UP ? 1 : 0,
controllerState.RIGHT ? 1 : 0,
controllerState.DOWN ? 1 : 0,
controllerState.LEFT ? 1 : 0,
controllerState.A ? 1 : 0,
controllerState.B ? 1 : 0,
controllerState.SELECT ? 1 : 0,
controllerState.START ? 1 : 0
];
this.worker.postMessageIgnoreResponse({
type: WORKER_MESSAGE_TYPE.SET_JOYPAD_STATE,
setJoypadStateParamsAsArray
});
}
enableDefaultJoypad() {
this.isEnabled = true;
ResponsiveGamepad.enable();
}
disableDefaultJoypad() {
this.isEnabled = false;
ResponsiveGamepad.disable();
}
}
export const WasmBoyController = new WasmBoyControllerService();