停用滑鼠加速功能,提供更優質的 FPS 遊戲體驗

網頁應用程式現在可以在擷取指標事件時停用滑鼠加速功能。

François Beaufort
François Beaufort

加速移動是一項人體工學功能,使用滑鼠或觸控板移動畫面上的指標時。這個 API 可緩慢移動,同時讓指標透過短動作穿越整個螢幕。具體來說,在您移動滑鼠的距離相同的情況下,如果距離移動得更快,畫面上的指標會移動得更久。

作業系統預設會啟用滑鼠加速功能。對於某些第一方視角遊戲 (常見的第一人稱射擊遊戲 (FPS),原始滑鼠輸入資料可用來控制相機旋轉,而無需加速調整。相同的物理動作、慢或快的旋轉會產生相同的旋轉結果。這可以讓專業玩家產生更好的遊戲體驗,並提高準確度。

Windows 10 設定中指標動作控制項的螢幕截圖。
Windows 10 設定中的遊標動作控制項。

從 Chrome 第 88 版開始,網頁應用程式可以透過新版 Pointer Lock API,切換加速和非加速滑鼠移動資料。

網路遊戲平台 (例如 Google StadiaNvidia GeForce Now) 運用了這些新功能來滿足 FPS 玩家的需求。

瀏覽器支援

  • 37
  • 13
  • 50
  • 10.1

資料來源

使用 API

要求指標鎖定

當電腦版應用程式隱藏指標圖示,以及解讀滑鼠動作 (例如在 3D 世界中瀏覽周圍) 時,標準詞彙會成為指標鎖定。

mousemove 文件事件的 movementXmovementY 屬性會指出自上次移動事件以來,滑鼠遊標移動了多少。但指標在網頁外移動時不會更新。

document.addEventListener("mousemove", (event) => {
  console.log(`movementX: ${event.movementX} movementY: ${event.movementY}`);
});

擷取滑鼠遊標 (或要求指標鎖定) 可讓您不必擔心指標在外移動。這項功能特別適合用於沉浸式網頁遊戲。指標鎖定時,所有滑鼠事件都會前往指標鎖定的目標元素。

在目標元素上呼叫 requestPointerLock() 以要求指標鎖定,並監聽 pointerlockchangepointerlockerror 事件來監控指標鎖定變更。

const myTargetElement = document.body;

// Call this function to request a pointer lock.
function requestPointerLock() {
  myTargetElement.requestPointerLock();
}

document.addEventListener("pointerlockchange", () => {
  if (document.pointerLockElement) {
    console.log(`pointer is locked on ${document.pointerLockElement}`);
  } else {
    console.log("pointer is unlocked");
  }
});

document.addEventListener("pointerlockerror", () => {
  console.log("pointer lock error");
});

停用滑鼠加速

使用 { unadjustedMovement: true } 呼叫 requestPointerLock(),即可停用滑鼠加速的 OS 層級調整功能,並存取原始滑鼠輸入。這樣一來,當指標鎖定時,mousemove 事件中的滑鼠移動資料就不會包含滑鼠加速。

請使用來自 requestPointerLock() 的新承諾,瞭解要求是否成功。

function requestPointerLockWithUnadjustedMovement() {
  const promise = myTargetElement.requestPointerLock({
    unadjustedMovement: true,
  });

  if (!promise) {
    console.log("disabling mouse acceleration is not supported");
    return;
  }

  return promise
    .then(() => console.log("pointer is locked"))
    .catch((error) => {
      if (error.name === "NotSupportedError") {
        // Some platforms may not support unadjusted movement.
        // You can request again a regular pointer lock.
        return myTargetElement.requestPointerLock();
      }
    });
}

不必放開指標鎖定,即可在加速和非加速的滑鼠移動資料之間切換。只要使用所需的選項,再次要求指標鎖定即可。如果該項要求失敗,原本的鎖定將保持不變,並且拒絕傳回的承諾。失敗的變更要求不會觸發任何指標鎖定事件。

瀏覽器支援

Pointer Lock API 支援各種瀏覽器。不過,自 2020 年 10 月起,只有以 Chromium 為基礎的瀏覽器 (例如 Chrome、Edge 等) 支援停用滑鼠加速的 OS 層級調整功能。如需更新資訊,請參閱 MDN 的「瀏覽器相容性」表格。

作業系統支援

ChromeOS、macOS Catalina 10.15.1 和 Windows 支援停用滑鼠加速的 OS 層級調整功能。Linux 將跟進。

範例

如要在 Glitch 上執行範例,即可使用 Pointer Lock API。請務必查看原始碼

實用連結

特別銘謝

感謝 James HollyerThomas SteinerJoe MedleyKayce BasquesVincent Scheib 發表這篇文章的評論。