tags:

views:

88

answers:

1

I'm trying to add springs to my physics engine, and while the algorithm itself works, they are incredibly stiff ( have to feed in values <= about 0.1 to get any visible motion out of it, and it has to be set extremely small in order to work properly). Any tips for improving the following code so it's not as stiff with values in the 0.1 to 1 range?

Vector2 posDiff = _a1.Position - _a2.Position;
Vector2 diffNormal = posDiff;
diffNormal.Normalize();
Vector2 relativeVelocity = _a1.Velocity - _a2.Velocity;
float diffLength = posDiff.Length();

float springError = diffLength - _restLength;
float springStrength = springError * _springStrength;
if (!float.IsPositiveInfinity(_breakpoint) && (springError > _breakpoint || springError < -1 * _breakpoint))
{
    _isBroken = true;
}
float temp = Vector2.Dot(posDiff, relativeVelocity);
float dampening = _springDampening * temp / diffLength;

Vector2 _force = Vector2.Multiply(diffNormal, -(springStrength + dampening));
_a1.ApplyForce(_force / 2);
_a2.ApplyForce(-_force / 2);
+1  A: 
Beta
I divide by two because i was under the impression that i get a force vector which, when applied to one of the bodies, completely resolves the spring error. As for my dampening being in the wrong direction, how do i fix it? i only translated a wikipedia formula into code or something. Will it be fixed if i swap the two variables i apply the dot product to?
RCIX
Hang on, is _force a force in the physics sense? Or is it more like a displacement, a sudden jump in location? If it's a physics force, you've calculated it correctly but you shouldn't divide it by two (each object feels the full force) and it won't necessarily make the spring instantly snap back to it's resting length (for instance, the objects might be heavy and the spring weak). If it's a sudden correction of length, you've calculated it incorrectly and your spring will act very un-springlike.
Beta
For the dampening, just change "springStrength + dampening" to "springStrength - dampening". (Swapping two vectors in a dot product does exactly nothing-- the dot product is commutative.)
Beta
_force is a displacement i think. I'l try these suggestions and see if they help, thanks!
RCIX