首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在GameController API中,是否需要持续轮询navigator.getGamepads()?

在GameController API中,是否需要持续轮询navigator.getGamepads()?
EN

Stack Overflow用户
提问于 2022-06-12 18:41:15
回答 1查看 101关注 0票数 0

最后编辑的

在GameController API中,是否需要持续轮询navigator.getGamepads()

我之所以这样问,是因为我对这个函数的单个调用返回了length = 0。

根据我的Mac的蓝牙系统首选项,我的Nimbus+游戏机连接的。

既然如此,我应该使用isetInterval` `并等待长度> 0吗?

编辑从这里开始:

Macintosh和蒙特利操作系统12.4:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2022-06-20 13:17:08

首先,您需要等待连接游戏垫,这通常需要通过按其中一个按钮“唤醒”游戏垫:

代码语言:javascript
复制
window.addEventListener('gamepadconnected', (event) => {
  console.log('✅  A gamepad was connected:', event.gamepad);
});

一旦连接到游戏垫,您就可以启动游戏循环:

代码语言:javascript
复制
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();

当游戏垫断开连接时,您应该停止轮询,这将通过一个事件通知您:

代码语言:javascript
复制
window.addEventListener('gamepaddisconnected', (event) => {
  console.log('❌  A gamepad was disconnected:', event.gamepad);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72594949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档