Skip to content

Instantly share code, notes, and snippets.

@typable
Last active Apr 28, 2021
Embed
What would you like to do?
Detect Gamepad input
const KEY_BINDING = {
0: 'A',
1: 'B',
2: 'X',
3: 'Y',
4: 'L1',
5: 'R1',
6: 'L2',
7: 'R2',
8: 'Option',
9: 'Menu',
10: 'L3',
11: 'R3',
12: 'Up',
13: 'Down',
14: 'Left',
15: 'Right',
16: 'Power',
17: 'Assist',
18: 'Capture'
};
function read_input(gamepad) {
let input = {
button: {},
axes: {}
};
for(let [ id, key ] of Object.entries(KEY_BINDING)) {
input.button[key] = gamepad.buttons[id].pressed;
}
input.axes['Left'] = {
x: gamepad.axes[0],
y: gamepad.axes[1]
};
input.axes['Right'] = {
x: gamepad.axes[2],
y: gamepad.axes[3]
};
return input;
}
// need to be in a loop
let gamepad = navigator.getGamepads()[0];
if(gamepad) {
let input = read_input(gamepad);
// input.button['A']
// input.axes['Right'].x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment