0

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?

Coding King2
  • 37
  • 1
  • 11
  • If by "lock the cursor" you mean using the new `Pointer Lock` API, that doesn't seem to be integrated with the p5.js library -- but you can still use it from your sketch since your sketch is just JavaScript code. p5.js.dom might useful for combining p5.js with other JavaScript libraries [See this](https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/issues/76) for an interesting discussion. – John Coleman Jun 13 '18 at 11:32
  • Yes but if the pointer is locked in the middle... how will it ever move? – Coding King2 Jun 13 '18 at 18:26
  • I don't have experience with that API. Perhaps you can focus your question a bit and post it with the `pointerlock` tag (which exists but doesn't seem to have much traffic). – John Coleman Jun 13 '18 at 19:19
  • You use [`movementX/Y`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/movementX) – zero298 Jun 13 '18 at 20:39

1 Answers1

1

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>
zero298
  • 25,467
  • 10
  • 75
  • 100