简体   繁体   English

在 GameController API 中,是否需要不断轮询 navigator.getGamepads()?

[英]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?在 GameController API 中,是否需要不断轮询navigator.getGamepads()

I ask because my single call to this function returns a length = 0.我问是因为我对这个函数的单次调用返回一个长度 = 0。

According to my Mac's Bluetooth System Preferences my Nimbus+ game pad is connected.根据我的 Mac 的蓝牙系统偏好设置,我的 Nimbus+ 游戏手柄连接。

Given that, should I use isetInterval` and wait for a length > 0?鉴于此,我是否应该使用 isetInterval` 并等待长度 > 0?

EDIT begins here:编辑从这里开始:

Macintosh with Monterey OS 12.4:带有 Monterey OS 12.4 的 Macintosh:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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