0

I'm developing a web game which uses a fixed physics timestep.

Currently I am doing all my physics and rendering in a requestAnimationFrame function.

This works perfectly, but requestAnimationFrame suspends and stops running when the user tabs out (to save processor performance I suppose).

As a result, if you tab out for like 30 minutes and then come back, the game has to simulate 30 minutes of physics in order to get back to the right spot.

This is very bad, as it causes the tab to freeze while the CPU cranks to 100% for the next 3 minutes while it runs all those physics calculations.

I think the only solution is to make the physics run while the tab is inactive, but I'm not sure how. I suppose I should only have the rendering in requestAnimationFrame, because it doesn't matter if that gets missed. But the physics need to be maintained.

Apparently setInterval also suspends when the user tabs out.

So, how should this be handled? I need a way to run physics every 16.6667 milliseconds regardless of whether the user is tabbed in or not. Is this possible? I've heard about WebWorkers but is that the actual solution? To put the entire game inside a WebWorker? What about when I want to change the DOM and things like that? Seems like a bit much.

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • 1
    Why would you need to run 30 minutes of physics? Can't you pause the game and resume it when they return? – Benjamin Ashbaugh Apr 24 '22 at 01:06
  • I wish I could say more but I found a couple of interesting answers here that maybe you'll find helpful: https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome and here the events to detect page visibility https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active – Diego D Apr 24 '22 at 01:07
  • It's multiplayer so can't pause – Ryan Peschel Apr 24 '22 at 01:08
  • 1
    @RyanPeschel You don't simulate physics on the client in a multiplayer game. You simply fetch the game state from the server (or, if distributed, the other peers) when the player returns to the tab. – Bergi Apr 24 '22 at 02:00
  • Since when? Tons of games simulate physics locally for client-side prediction in real-time games and use the server only for authoritative correction. – Ryan Peschel Apr 24 '22 at 02:06
  • Prediction, yes. But you don't need to do any predictions for rendering when the player is not viewing the tab. Then when they come back, just update your game state with the authoritative data. – Bergi Apr 24 '22 at 02:59

0 Answers0