pmndrs / use-p2

šŸ‘‹šŸ’£ 2d physics hooks for @react-three/fiber
https://p2.pmnd.rs
MIT License
147 stars 9 forks source link

Physics simulation speeds up after page visibility change #7

Open mklasinc opened 2 years ago

mklasinc commented 2 years ago

To replicate: Run any demo, e.g. KinematicCharacterController, click on another tab, wait for a couple of seconds, then go back to the demo tab, and the physics simulation runs at super speed for a bit before it goes back to normal. The issue is the same in p2.js (http://schteppe.github.io/p2.js/examples/canvas/character.html)

The length of this glitch seems proportional to the time you spent away from the page, so i thought it's because the physics engine is accumulating time while the page is not active, and then it tries to catch up the simulation after the page is active again? I'm not sure, just guessing. (also I'm running Mac M1)

Fix: This fixed it for me, but maybe there's a better way?

   const [isPageActive, setIsPageActive] = useState(true);

   useFrame((state, delta) => {
      if(!isPageActive) return
      world.step(fixedTimeStep, delta, maxSubSteps);
    })

    useEffect(() => {
      function onPageVisibilityChange() {
        if (document.visibilityState === 'visible') {
          requestAnimationFrame(() => setIsPageActive(true))
        } else {
          setIsPageActive(false);
        }
      }
      document.addEventListener('visibilitychange', onPageVisibilityChange);
      return () => document.removeEventListener('visibilitychange', onPageVisibilityChange);
    }, [])