I have two gamepads that are connected via usb and they are of the same exact type. How do I differentiate them when they have the same fields? I could use index, but what happens when I connect them again to the computer those indexes might be swapped (these gamepads have different functionalities). Also I think the indexes might get swapped during runtime. Is there a UUID or something?
Asked
Active
Viewed 93 times
1 Answers
0
You could keep your own array of Gamepads, and create your own ID for each one connected. I'm not sure how the Gamepad API works and It would be weird if the indexes swap, but this solution could work around that.
let gamepads = [];
// On Connect add it to list of gamepads
window.addEventListener("gamepadconnected", function(e) {
let gamepad = navigator.getGamepads()[e.gamepad.index];
// You should find some better way to create a unique ID (Can use UUID's)
let uniqueId = Math.floor(Math.random() * 10000);
gamepads.push({gamepad: gamepad, uniqueId: uniqueId});
});
// On disconnect
window.addEventListener("gamepaddisconnected", function(e) {
let disconnectedGamepad = gamepads.find((gamepad) => {
return gamepad.index === e.gamepad.index;
});
gamepads = gamepads.splice(disconnectedGamepad.index, 1);
});

Eric E
- 572
- 1
- 4
- 16