If you want well defined behavior, you should consider perpetuating the oscillations yourself. I will assume, for simplicity, that we are working with a simple spring-mass-damper system where the spring and damper behavior is encapsulated in a b2DistanceJoint
.
The basic idea is to evaluate the total energy (kinetic + potential) of the system and apply a force if this is below a certain threshold. The total energy of the system at any instant is given by:
where m
is the mass of the body at the end of the spring, k
is the spring coefficient, and x
is the displacement from the rest length. k
can be related to the frequency of the distance joint through the equation:
Plugging this in and simplifying gives:
All of the variables on the right hand side can be evaluated (with the help of box2d). Once you have calculated the energy, compare it with a reasonable threshold value. If it exceeds that threshold, then your spring is under significant tension or compression and/or the mass has a high velocity; in this case we don't need to do anything. If the energy falls below the threshold, then apply some small force dF
along the spring axis, in the direction that the mass is currently moving.
Here's how I might implement it (in c++)
/* ... */
b2Body springBody;
b2DistanceJoint spring;
double restLength;
double Ethresh; //Threshold energy. Set to reasonable value.
double dFM; //Small force. Set to reasonable value.
// in time loop
/* ... */
/* Assign spring body and distance joint */
double m = springBody.GetMass();
b2Vec2 vel = springBody.GetLinearVelocity();
double vmag = vel.Length(); //Assuming the body is traveling along the spring axis
double w = spring.GetFrequency();
double x = spring.GetLength() - restLength;
double E = 0.5*m*(vmag*vmag + w*w*x*x);
if(E < Ethresh){
b2Vec2 dF = (vel/vmag)*dFM;
springBody.applyForce(dF);
}
/* ... */
If you have a more complicated system (e.g. distance joints attached to bodies which are joined to tertiary bodies, etc...) this will of course invalidate the theory, but I believe this approach will produce visually believable results for many different setups.