Thursday, May 26, 2011

One line of code

That's what it's all about: one line of code (!).

Rolling Coaster is a game where you control a ball on a racetrack. You can accelerate, break and speed-boost. The physics that govern the movement of the ball is derived from the torque/angular velocity and the forces acting on the ball: gravity and friction. Some of the equations that are needed look like this:


It's then a simple task (*) to derive the equation of motion for a rolling ball that may slide on the surface depending on friction.

After that, a numerical solution is needed, which is simply to replace the differentials with the actual differences during the integrating timestep. Presto! An advanced model of a rolling, sliding ball is created!

In the C# code it looks like this:

   // Calculate friction wanted by ball   float A = dt * (1.0f / I + 1.0f / (r2 * m));
   Vector3 Bvec = -(1.0f / r2 * Vector3.Cross(radius, v0 + dt / m * gravAlong) + w0 + K * dt);
   Vector3 Bvec0 = 1.0f / A * Bvec;

   // Value of friction
   float fricWanted = Bvec0.Length() / rollinProp.radius;

That's not one line... it's, uh, 4 lines. Yes... and just a couple of more lines are needed to make a game out of it, right now 58518 and still counting.

1 comment: