光标锁定时如何获取mouseMovement?

How to get mouseMovement when cursor is locked?

在寻找将光标锁定在 processing/p5.js/javascript 中的方法时,我意识到即使我想通了,我也无法检测到鼠标移动。人们如何在典型的 fps 游戏中做到这一点?

您利用了 movementX/Y,它在光标锁定时仍在更新。

MDN documentation:

When Pointer lock is enabled, the standard MouseEvent properties clientX, clientY, screenX, and screenY are held constant, as if the mouse is not moving. The movementX and movementY properties continue to provide the mouse's change in position. There is no limit to movementX and movementY values if the mouse is continuously moving in a single direction. The concept of the mouse cursor does not exist and the cursor cannot move off the window or be clamped by a screen edge.


请注意,由于沙盒限制,下面的代码片段不适用于 Stack Overflow。参见:iframe limitations

const foo = document.getElementById("foo");
const button = document.getElementById("btn");
const dX = document.getElementById("x");
const dY = document.getElementById("y");

function lockPointer(elem) {
  if (elem.requestPointerLock) {
    elem.requestPointerLock();
  } else if (elem.webkitRequestPointerLock) {
    elem.webkitRequestPointerLock();
  } else if (elem.mozRequestPointerLock) {
    elem.mozRequestPointerLock();
  } else {
    console.warn("Pointer locking not supported");
  }
}

foo.addEventListener("mousemove", e => {
  const {
    movementX,
    movementY
  } = e;

  dX.innerHTML = movementX;
  dY.innerHTML = movementY;
});

btn.addEventListener("click", e => {
  lockPointer(foo);
});
#foo {
  width: 100px;
  height: 100px;
  background-color: black;
}
<canvas id="foo"></canvas>
<button id="btn">Lock</button>
<div>X: <span id="x"></span> | Y: <span id="y"></span></div>

它不起作用请帮忙,它不会改变 y 位置的值但保持不变我的代码是

    function getmouse(event) {
      document.getElementById("canvas_parent").style.top = 
    (event.movementY - (event.movementY * 2)) + "px"
    }