Friday, April 3, 2015

Getting the Physics Step Right

After porting the Ash framework to coffeescript it seemed to me the next logical step was to use Box2d to calculate the asteroid movement. This actually made the game fun - now the asteroids bounce off each other, and stuff...

But performance on android suffered. Especially in the Cocoon Canvas+ environment, which puzzled me because I'm using the native Box2d plugin. Until I found this excellent post from Allan Bishop, which explained very well what I was running into.

I had been naively calling world.Step() from my game loop, which is driven by requestAnimationFrame. This works ok in the chrome desktop browser, until there is a performance load, and not ok at all in chrome for android. The problem is, when performance suffers, the frame rate starts to slip, resulting in the 'jiggly' physics I was seeing. There are a couple of ways to work with this:

  • Fixed Time Step
  • Interpolate the time delta to sync with the frame rate

So, splitting my PhysicsSystem into two classes, I implemented both. 

One, FixedPhysicsSystem, uses setInterval to cause world.Step() to be called every 1/60 seconds. 
The other, the SmoothPhysicsSystem - implements Allan's ActionScript example.

As it turns out, I need both.  When using the Cocoon Box2d plugin, using an absolute value of 1/60 to advance the physics works well, but interpolation makes it worse. I found the opposite to be true in the browser. So I check to see if the plugin is present, and use the appropriate physics system class.

No comments:

Post a Comment