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?
You leverage movementX/Y
which are still updated while the cursor is locked.
See the 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.
Note that the snippet below will not work on Stack Overflow due to sandboxing restrictions. See: 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>