chandlerprall / GoblinPhysics

Collision Detection & Response in JavaScript
http://www.goblinphysics.com
Other
147 stars 18 forks source link

Use timestamps instead of 1/60 constant. #69

Closed trusktr closed 7 years ago

trusktr commented 7 years ago

I see here you're dividing 1 by 60. If the calculations take too long (longer than 16.66ms), then the animation will slow down.

If you use the timestamp passed into the requestAnimationFrame callback instead, then the animations can continue at the same speed even if the frame rate is lower.

trusktr commented 7 years ago

Something like this: https://github.com/chandlerprall/GoblinPhysics/pull/70

chandlerprall commented 7 years ago

Indeed. However, it can be more problematic when passing non-deterministic values as a step. If you re-run the simulation you will get different results because the given time deltas won't be the same. Number drift, floating point precision, etc, all come into play to make this a Hard Decision that each implementation needs to decide for themselves.

Another consideration is that a longer step value means the simulation is less accurate - there's more time for objects to drift into each other which affects contact resolution. This is why the step function accepts a second parameter max_step, so you could pass in a time_delta of 1 second with a max_step of 100ms and Goblin will break the call into 10 separate steps and simulate them individually.

Even with a max_step, passing a non-deterministic time delta is still problematic as the full time delta specified is simulated. Passing 45ms time_delta with 20ms max_step will result in 3 simulation steps: 20ms + 20ms + 5ms. It would be better to identify how much time has passed as a multiple of the time step, so if 45ms have passed it would be better to pass 40 instead of 45. The simulation would still lag some from this but it is far less perceptible.

trusktr commented 7 years ago

Interesting! Thanks for those insights. If re-running a simulation is desired, maybe the timesteps can be recorded for static use later. I also see what you mean about the physics accuracy with larger time steps. I've heard of possible techniques where if an object is going really fast (it would completely pass through an object in the next frame), the engine takes that into account. Interesting food for thought!