schteppe / p2.js

JavaScript 2D physics library
Other
2.64k stars 330 forks source link

Game speeds up after window blur > returning, with requestAnimationFrame #229

Closed AndrewRayCode closed 8 years ago

AndrewRayCode commented 8 years ago

My game uses p2.js for physics, and I update the world every rAF with:

world.step( 1 / 60, delta, 3 )

However, when I blur my game and come back later, all of my physics simulations are sped up. I saw this once on a p2.js demo as well (or maybe it was a cannon.js demo). I can't reproduce it now with the demos but it still happens with my game.

I haven't done much digging into it yet, but are you aware of what might be causing the problem? is there an easy solution?

schteppe commented 8 years ago

Hi. Yes, I'm aware, but I've not built this into p2 because it's too much coupled to the game loop and depends on how the particular target game works. Perhaps the fix could be built into the Demo class, but haven't gotten there yet.

Anyway. The reason why this happens is because the time delta you get from RAF is too big. The fix is to detect the window unfocusing / visibility change and when that happens, set the next time delta to zero. Or pause your game completely, it's up to you.

This is how Phaser checks for visibility change, should be enough to get you started: https://github.com/photonstorm/phaser/blob/master/src/core/Stage.js#L235

AndrewRayCode commented 8 years ago

Ah cool! I figured you would be aware of a quick fix.

danneu commented 8 years ago

Another approach is to use setTimeout (or, less ideal, setInterval) to schedule your updates which will slow down to a minimum resolution of 1000ms when the user tabs out.

Just ensure you supply world.step() enough maxSubSteps to cover 1000ms and your game will be able to continue in the background.

Since requestAnimationFrame stops firing entirely when the user tabs out, you can reserve it for your render(world) call.