Gamepad:buttons 屬性

Baseline 已廣泛支援

此特性已得到良好確立,可跨多種裝置和瀏覽器版本使用。自 2017 年 3 月起,所有瀏覽器均支援此特性。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

buttons 屬性是 Gamepad 介面的一個屬性,它返回一個 GamepadButton 物件陣列,這些物件代表裝置上的按鈕。

陣列中的每個條目在按鈕未按下時為 0,在按鈕按下時為非零值(通常為 1.0)。

一個 GamepadButton 物件陣列。

示例

根據按鈕的型別,我們需要訪問 GamepadButton.valueGamepadButton.pressed 屬性。本示例支援兩者。

js
function gameLoop() {
  const gp = navigator.getGamepads()[0];

  if (gp.buttons[0].value > 0 || gp.buttons[0].pressed) {
    b--;
  } else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed) {
    a++;
  } else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed) {
    b++;
  } else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed) {
    a--;
  }

  ball.style.left = `${a * 2}px`; // ball is a UI widget
  ball.style.top = `${b * 2}px`;

  requestAnimationFrame(gameLoop);
}

規範

規範
Gamepad
# dom-gamepad-buttons

瀏覽器相容性

另見

使用遊戲手柄 API