forked from neogeek/gamepad.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
126 lines (105 loc) · 3.94 KB
/
index.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
const Bowser = require('bowser');
const mappings = require('./mappings.json');
const _requestAnimation = new Set('_requestAnimation');
const _previousGamepadsState = new Set('_previousGamepadsState');
const browser = Bowser.getParser(window.navigator.userAgent);
const AXES_THRESHOLD = 0.3;
class Gamepad {
[_requestAnimation] = null;
[_previousGamepadsState] = null;
listeners = [];
start = () => {
this._requestAnimation = window.requestAnimationFrame(this.tick);
};
stop = () => {
window.cancelAnimationFrame(this._requestAnimation);
};
on = (type, id, callback) => {
this.listeners[this.listeners.length] = { type, id, callback };
};
off = (type, id) => {
this.listeners[this.listeners.length].splice(
this.listeners.findIndex(
listener => listener.type === type && listener.id === id
),
1
);
};
tick = () => {
const gamepads = [].slice
.call(window.navigator.getGamepads())
.filter(gamepad => gamepad)
.map(({ id, index, buttons, axes }) => {
const mapping = mappings.find(
mapping =>
mapping.id === id &&
mapping.browser === browser.getBrowserName() &&
mapping.os === browser.getOSName()
);
if (!mapping) {
throw new Error(`${id} not supported by gamepad.js`);
}
return {
id,
index,
buttons: Object.keys(mapping.buttons).reduce((all, key) => {
return {
...all,
[key]: buttons[mapping.buttons[key]]
};
}, {}),
axes,
mapping
};
});
gamepads.map(gamepad => {
const previousGamepadState = this._previousGamepadsState.find(
({ index }) => gamepad.index === index
);
this.listeners
.filter(({ id }) => gamepad.buttons[id])
.filter(({ type, id }) => {
switch (type) {
case 'pressed':
return (
gamepad.buttons[id].pressed &&
(!previousGamepadState ||
!previousGamepadState.buttons[id].pressed)
);
case 'held':
return gamepad.buttons[id].pressed;
case 'released':
return (
!gamepad.buttons[id].pressed &&
previousGamepadState &&
previousGamepadState.buttons[id].pressed
);
default:
return false;
}
})
.map(({ callback, id }) =>
callback({
id,
gamepadIndex: gamepad.index,
value: gamepad.buttons[id].value
})
);
});
gamepads.map(gamepad => {
this.listeners
.filter(({ type }) => type === 'axes')
.filter(({ id }) => Math.abs(gamepad.axes[id]) > AXES_THRESHOLD)
.map(({ callback, id }) =>
callback({
id,
gamepadIndex: gamepad.index,
value: gamepad.axes[id]
})
);
});
this._previousGamepadsState = gamepads;
this._requestAnimation = window.requestAnimationFrame(this.tick);
};
}
module.exports = Gamepad;