Gamepad: axes property

Baseline 已广泛支持

此特性已得到良好确立,可跨多种设备和浏览器版本使用。自 2017 年 3 月起,所有浏览器均支持此特性。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

Gamepad 接口的 axes 属性返回一个数组,表示设备上存在的轴控件(例如,模拟摇杆)。

数组中的每个条目都是一个介于 -1.0 到 1.0 之间的浮点值,表示轴位置,其中 -1.0 是最低值,1.0 是最高值。

一个数字数组。

示例

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

  let a = 0;
  let b = 0;
  if (gp.axes[0] !== 0) {
    b -= gp.axes[0];
  } else if (gp.axes[1] !== 0) {
    a += gp.axes[1];
  } else if (gp.axes[2] !== 0) {
    b += gp.axes[2];
  } else if (gp.axes[3] !== 0) {
    a -= gp.axes[3];
  }

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

  const start = requestAnimationFrame(gameLoop);
}

规范

规范
Gamepad
# dom-gamepad-axes

浏览器兼容性

另见

使用游戏手柄 API