How to activate PointerLockControls only when clicking a button?

Viewed 219

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} />
}
0 Answers
Related