schteppe / p2.js

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

Corrected example in comment for World.step with interpolation #254

Closed TomWHall closed 7 years ago

schteppe commented 8 years ago

Just ran this code in a jsfiddle and I got a negative value for deltaTime in the first frame... Most of the times the value is positive though. I'm not sure how this could happen, since performance.now() is run before requestAnimationFrame?

Thanks!

TomWHall commented 8 years ago

Hmmm, I'm not sure either. The Mozilla docs state that t is "the current time when callbacks queued by requestAnimationFrame begin to fire", which I thought must be after the startTime assignment. Perhaps it's safest to forget the startTime and allow the very first iteration to do a 0 size step? I.e. like this? Would that cause a problem?

schteppe commented 8 years ago

Using timeSinceLastCalled=0 for the first step would make the world take one fixed step forward, no matter if using variable timesteps or fixed. I think avoiding the first zero-step would be good. Maybe if(deltaTime){ world.step(...) }?

TomWHall commented 8 years ago

Sorry for the delay. I hadn't realized that was the world step behaviour with a 0 time step. You're right, although it would be nice to achieve a way where that loop doesn't need to do any checks like this every time (even like my || check) - but maybe the overhead is negligible?

schteppe commented 7 years ago

Checking once per frame is totally negligible. I'm more concerned about the learning part, as this is an important example code snippet for beginners.

What do you think about this? https://github.com/schteppe/p2.js/commit/5b6b2efd74b30591e1a7d8f6eac4a587da0cbd60

TomWHall commented 7 years ago

Yeah, that looks good to me. Should there be "var" for the timeSeconds and deltaTime local variables?

schteppe commented 7 years ago

Correct! Thanks.