soulwire / Coffee-Physics

A simple, lightweight physics engine written in CoffeeScript
MIT License
1.06k stars 89 forks source link

Attraction and Repulsion increased #14

Closed Blackhart closed 10 years ago

Blackhart commented 10 years ago

Hello,

In the Coffee-Physics example, when you switch tabs and then return on the effect. Attraction and repulsion are considerably increased (proportionally to the time that you stay on the other tab).

soulwire commented 10 years ago

Hi,

This is because the animation loop stops running so there's a huge delta time when you get back to the tab. The integrator tries to run more loops to catch up, essentially making the simulation speed up until the clock is synced. It's expected behavior but not really desirable in this case (the feature is there in case, for example, some frames are dropped; then the simulation will catch up to eventually be time accurate again.)

You can override this by either listening for window focus and setting the buffer to 0, or checking in your draw loop.

if ( physics._buffer > 1 ) {
    physics._buffer = 0;
}

The 1 is arbitrary and should relate to how many seconds you consider a tab switch can be assumed from. At any point, clearing the buffer like this will create parity between the internal physics clock and the browser clock.