简体   繁体   中英

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. 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?

在此处输入图片说明

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM