備忘録

備忘録

Webブラウザでゲームパッドを利用する方法

Ⅰ. はじめに

タイトルの通り「Webブラウザでゲームパッドを利用する方法」です。

Ⅱ. 手順

1. サンプルプログラムを書く

index.html

<!DOCTYPE html>
<html>
<body>
  <script src="/script.js"></script>
</body>
</html>

script.js

const buttonPressStates = []
const buttons = [
  { id: 12, label: 'UP' },
  { id: 13, label: 'DOWN' },
  { id: 14, label: 'LEFT' },
  { id: 15, label: 'RIGHT' },
]

function onAnimationFrame() {
  const gamepads = navigator.getGamepads()
  const gamepad = gamepads[0]

  for (const i of buttons.map(x => x.id)) {
    if (!buttonPressStates[i] && gamepad.buttons[i].pressed) {
      console.log(`${buttons.find(x => x.id === i).label} pressed`)
      buttonPressStates[i] = true
    } else if (buttonPressStates[i] && !gamepad.buttons[i].pressed) {
      console.log(`${buttons.find(x => x.id === i).label} released`)
      buttonPressStates[i] = false
    }
  }

  window.requestAnimationFrame(onAnimationFrame)
}

window.addEventListener('gamepadconnected', () => {
  window.requestAnimationFrame(onAnimationFrame)
})

実行結果

以下2種類のゲームパッドで動作確認済み

  • HD-6500
  • Joy-Con