简体   繁体   中英

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

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

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

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