3

I am using the "PointerLockControls" class and I would like to be able to disable the mouse lock when I am in my menu. I want the only way to lock the mouse is to press the button for that. Similarly to what is done here:

https://classic.minecraft.net/

Currently, no matter where I click on the canvas, it activates the pointer lock.

I tried to make the following code, where “ready” is true only when we press a button. Which seems to work. However, it can lock even when ready is false. I tough .connect()/.disconnect() would allow to deactivate the lock. I also tried to have a div in front of the whole canvas in order to avoid clicking the canvas, which theoretically should work as well. But I can’t find a way to avoid the click to go through the div.

function PointerLocks({ ready, setReady }) {
  const controls = useRef()

  useEffect(() => {
    if (ready) {
      controls.current.connect()
      controls.current.lock()
    }
  }, [ready])

  const onUnlockHandle = useCallback(() => {
    setReady(false)
    controls.current.disconnect()
  })

  return <PointerLockControls ref={controls} maxPolarAngle={Math.PI - 0.0001} minPolarAngle={0.0001} onUnlock={onUnlockHandle} />
}
Raym
  • 51
  • 6

1 Answers1

2

I have been using this (as a click event on, for example a button outside the 'game') as a way of forcing the pointer to disengage at certain points (bit hacky):

onClick={() => setTimeout(() => {pointerControls.current.unlock()},100)}

For locking, I use:

pointerControls.current.connect();
setTimeout(() => {pointerControls.current.lock()},110);

The higher timeout for lock overrides the 100 in the unlock if there is ever a conflict of html element click events.

These might also help:

https://discourse.threejs.org/t/unable-to-use-pointer-lock-api/11092

https://discourse.threejs.org/t/how-to-activate-deactivate-pointerlockcontrols/33618/4

timhc22
  • 7,213
  • 8
  • 48
  • 66