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

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

François Beaufort
François Beaufort

使用滑鼠或觸控板在螢幕上移動指標時,加速移動功能可提供符合人體工學的體驗。可透過緩慢移動精確移動游標,也能透過快速的短促動作,讓游標移動到螢幕的任何位置。具體來說,如果滑鼠移動的實體距離相同,但移動速度較快,螢幕上的指標就會移動得更遠。

作業系統預設會啟用滑鼠加速功能。對於某些第一人稱遊戲 (通常是第一人稱射擊遊戲),系統會使用原始滑鼠輸入資料控制攝影機旋轉,而不調整加速度。無論實體動作緩慢或快速,都會產生相同的旋轉效果。專業電競玩家表示,這可帶來更優質的遊戲體驗,並提高準確度。

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

從 Chrome 88 版開始,由於更新了指標鎖定 API,網頁應用程式可以切換加速和非加速滑鼠移動資料。

Google StadiaNvidia GeForce Now 等網頁遊戲平台已採用這些新功能,滿足 FPS 遊戲玩家的需求。

Browser Support

  • Chrome: 37.
  • Edge: 13.
  • Firefox: 50.
  • Safari: 10.1.

Source

使用 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");
});

停用滑鼠加速

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

使用 requestPointerLock() 傳回的新 Promise,瞭解要求是否成功。

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();
      }
    });
}

你可以在不放開指標鎖定的情況下,切換滑鼠移動資料的加速與非加速模式。只要使用所需選項再次要求指標鎖定即可。如果該要求失敗,原始鎖定狀態會維持不變,且傳回的 Promise 會遭到拒絕。如果變更要求失敗,系統就不會觸發指標鎖定事件。

瀏覽器支援

Pointer Lock API 在各個瀏覽器中都獲得良好支援。不過,自 2020 年 10 月起,只有以 Chromium 為基礎的瀏覽器 (例如 Chrome、Edge 等) 支援停用滑鼠加速度的作業系統層級調整功能。如需最新資訊,請參閱 MDN 的「瀏覽器相容性」表格。

作業系統支援

ChromeOS、macOS Catalina 10.15.1 和 Windows 支援停用作業系統層級的滑鼠加速調整功能。Linux 版隨後推出。

範例

您可以執行範例,試用指標鎖定 API。

實用連結

特別銘謝

感謝 James HollyerThomas SteinerJoe MedleyKayce BasquesVincent Scheib 審查本文。