photonstorm/phaser — pull request #266 by cocoademon (2013-12-17 03:56:55+00:00)
Title: Physics instability fix

Commit 1eca16a9489e97d30384d4d6007dd9ef22f0a3ac was supposed to add a time-dependence to the velocity calculation. However, in practice what is does is:

- Multiply by game.time.physicsElapsed (which in many cases is 1/60)
- Remultiply by a fixed 60

This causes real problems with drag calculations. In particular, when velocity approaches zero when frame rate is < 60fps, the following happens:

- physicsElapsed = 1/30
- currentVelocity = 1
- Due to drag, computeVelocity calculates a desired velocity of 0
- _velocityDelta is therefore (0-1) * elapsed * 0.5 * 60 = -1 * 60/60 = -1;
- _velocityDelta is applied twice, yielding a new velocity of -1

It gets worse with lower framerates:

- physicsElapsed = 1/20
- _velocityDelta is therefore (0-1) * elapsed * 0.5 * 60 = -1 * 60/40 = -1.5;
- _velocityDelta is applied twice, yielding a new velocity of -2, an *increase* in velocity due to drag

See Rafael Oliveira's test example: http://rafaholiveira.com.br/test-drag/

Commit 1eca16a9489e97d30384d4d6007dd9ef22f0a3ac *did* appear to fix variable gravity due to framerate, however this is probably because the gravity calculations didn't take framerate into account at all anyway.

This PR also includes a fix for the non-variable application of gravity. I've tested it on the examples and my own games and it looks ok, but would appreciate your feedback.

I also removed the axis stuff from the computeVelocity method as it seemed less clean.

Regarding the branching, I've made a jsPerf to see which is better:
http://jsperf.com/multiply-vs-branch

The existing branching approach looks much better when most things have zero gravity and acceleration, but the "just multiply" approach is (obviously) better if most things have gravity and acceleration. It's a wash if everything has just gravity (eg lots of particles).