Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Physics simulation speeds up after page visibility change #7

Open
mklasinc opened this issue Mar 18, 2022 · 0 comments
Open

Physics simulation speeds up after page visibility change #7

mklasinc opened this issue Mar 18, 2022 · 0 comments

Comments

@mklasinc
Copy link

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);
    }, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant