While looking for way to lock the cursor in processing/p5.js/javascript I realized that even once I figured that out I would not be able to detect mouse movement. How do people do it in typical fps games?
问问题
646 次
1 回答
1
您可以利用movementX/Y
在光标锁定时仍会更新的内容。
请参阅MDN 文档:
启用指针锁定时,标准 MouseEvent 属性 clientX、clientY、screenX 和 screenY 保持不变,就好像鼠标没有移动一样。移动X 和移动Y 属性继续提供鼠标的位置变化。如果鼠标在一个方向上连续移动,则移动 X 和移动 Y 值没有限制。不存在鼠标光标的概念,光标不能移出窗口或被屏幕边缘夹住。
请注意,由于沙盒限制,下面的代码段不适用于 Stack Overflow。请参阅:iframe 限制
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>
于 2018-06-13T20:53:53.250 回答