[英]How do I differentiate two gamepads of the same type?
I have two gamepads that are connected via usb and they are of the same exact type.我有两个通过 USB 连接的游戏手柄,它们的类型完全相同。 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?
有 UUID 之类的吗?
You could keep your own array of Gamepads, and create your own ID for each one connected.您可以保留自己的游戏手柄阵列,并为每个连接的游戏手柄创建自己的 ID。 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.
我不确定 Gamepad API 是如何工作的,如果索引交换会很奇怪,但是这个解决方案可以解决这个问题。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.