0

EDITED at end!

Within the GameController API, is continuously polling of navigator.getGamepads() required?

I ask because my single call to this function returns a length = 0.

According to my Mac’s Bluetooth System Preferences my Nimbus+ game pad is connected.

Given that, should I use isetInterval` and wait for a length > 0?

EDIT begins here:

Macintosh with Monterey OS 12.4:

Safari (15.5) reports length = 0
Firefox (102.0b6) reports length = 0
Chrome (102.0.5005.115) reports length = 4,
   but each in the array being = null
  • Nimbus+ is MFi certified so it should be enumerated through Game Controller API. I'd expect it to work in Chrome and Safari but not Firefox since `DarwinGamepadService` only implements support for HID gamepads. Try again on https://gamepad-tester.com and make sure you press a button on the gamepad after loading the page. For privacy reasons, the API avoids exposing information about connected gamepads until there's evidence you're actually using them. – nondebug Jun 13 '22 at 20:16
  • I just took your advice and started pressing buttons etc and it showed. Thanks!!! –  Jun 13 '22 at 22:17
  • Spoke too soon. Yes it definitely registers the connection with your awesome code. **But** `navigator.getGamepads()` **still** states not connected –  Jun 16 '22 at 03:58
  • Whoopie … The lightbulb in my brain just came on for determining if a gamepad is connected or not. Turns out you wait for a connected event associated with the browser window and once detected you can find out about the buttons and how to use the buttons to move game pieces around. So, you call navigator.getGamepads() **within** the waitFor… calls. Not too shabby for being at this for 3.5 weeks. –  Jun 17 '22 at 09:53

1 Answers1

0

You first wait for the gamepad to be connected, which typically requires "waking" the gamepad by pressing one of its buttons:

window.addEventListener('gamepadconnected', (event) => {
  console.log('✅  A gamepad was connected:', event.gamepad);
});

Once the gamepad is connected, you start your game loop:

const pollGamepad = () => {
  // Always call `navigator.getGamepads()` inside of
  // the game loop, not outside.
  const gamepads = navigator.getGamepads();
  for (const gamepad of gamepads) {
    // Disregard empty slots.
    if (!gamepad) {
      continue;
    }
    // Process the gamepad state.
    console.log(gamepad);
  }
  // Call yourself upon the next animation frame.
  // (Typically this happens every 60 times per second.)
  window.requestAnimationFrame(pollGamepad);
};
// Kick off the initial game loop iteration.
pollGamepad();

You should stop polling when the gamepad gets disconnected, which you'll be informed of via an event:

window.addEventListener('gamepaddisconnected', (event) => {
  console.log('❌  A gamepad was disconnected:', event.gamepad);
});
DenverCoder9
  • 2,024
  • 11
  • 32