Question

Does anyone know any c++/opengl sourcecode demos for 2D rigid body physics using runge kutta?

I want to build a physics engine but I need some reference code to understand better how others have implemented this.

Was it helpful?

Solution

There are a lot of things you have to take care to do this nicely. I will focus on the integrator implementation and what I have found works good for me.

For all the degrees of freedom in your system implement a function to return the accelerations a as a function of time t, positions x and velocities v. This should operate on arrays or vectors of quantities and not just scalars.

a = accel(t,x,v);

After each RK step evaluate the acceleration to be ready for the next step. In the loop then do this:

{
   // assume t,x[],v[], a[] are known
   // step time t -> t+h and calc new values
   float h2=h/2;
   vec q1 = v + h2*a;
   vec k1 = accel(t+h2, x+h2*v, q1);
   vec q2 = v + h2*k1;
   vec k2 = accel(t+h2, x+h2*q1, q2);
   vec q3 = v + h*k2;
   vec k3 = accel(t_h, x+h*q2, q3);
   float h6 = h/6;
   t = t + h;
   x = x + h*(v+h6*(a+k1+k2));
   v = v + h6*(a+2*k1+2*k2+k3);
   a = accel(t,x,v);
}

Why? Well the standard RK method requires you to make a 2xN state vector, but the derivatives of the fist N elements are equal to the last N elements. If you split the problem up to two N state vectors and simplify a little you will arrive at the above scheme for 2nd order RK.

I have done this and the results are identical to commercial software for a plan system with N=6 degrees of freedom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top