The trembling and unintended slow movement of objects at rest in your 2D physics engine is likely due to the way friction is being calculated and applied in your PenetrationConstraint class. Specifically, the issue arises because the friction model doesn't properly distinguish between static and kinetic (dynamic) friction, causing small friction impulses to be applied even when the objects are supposed to be stationary. These small impulses can accumulate over time due to numerical errors, leading to the observed jittering and drifting.
Explanation:
In real-world physics, static friction prevents objects at rest from starting to move until an external force exceeds a certain threshold (the maximum static friction force). Once in motion, kinetic friction (usually slightly less than static friction) opposes the motion but doesn't prevent it from continuing. In your code, the friction model doesn't account for this distinction and always applies friction impulses based on the relative tangential motion, regardless of how small that motion is.
Here's what's happening in your code:
-
Friction Coefficient Calculation:
friction = std::max(a->friction, b->friction);
This line selects the larger friction coefficient between the two bodies, which is acceptable. However, it doesn't account for static vs. kinetic friction.
-
Friction Impulse Calculation and Clamping:
const float maxFriction = cachedLambda[0] * friction;
cachedLambda[1] = std::clamp(cachedLambda[1], -maxFriction, maxFriction);
You calculate the maximum allowable friction impulse based on the normal impulse (cachedLambda[0]) and the friction coefficient. Then you clamp the friction impulse (cachedLambda[1]) within this range. However, this assumes that any tangential motion, no matter how small, results in a friction impulse, which isn't accurate for static friction.
-
Accumulation of Small Friction Impulses:
Since even minute tangential velocities produce friction impulses, these small impulses can accumulate due to numerical inaccuracies (like floating-point errors), causing the bodies to jitter or drift when they should remain at rest.
Solution: Implement Static Friction Threshold
To fix this issue, you need to modify your friction model to include a static friction threshold. This involves checking the relative tangential velocity between the contact points. If the tangential velocity is below a certain small threshold (indicating that the bodies are at rest or nearly at rest), you should cancel out the tangential velocity completely (simulate static friction) as long as it's within the maximum static friction force. If the tangential force required to stop the motion exceeds this maximum, then the bodies should start moving and kinetic friction should apply.
Modified Code:
Here's how you can modify your Solve() function to implement this:
void PenetrationConstraint::Solve() {
const VecN V = GetVelocities();
const MatMN invM = GetInvM();
const MatMN J = jacobian;
const MatMN Jt = jacobian.Transpose();
// Compute lambda using Ax=b
MatMN lhs = J * invM * Jt; // A
VecN rhs = J * V * -1.0f; // b
rhs[0] -= bias;
VecN lambda = MatMN::SolveGaussSeidel(lhs, rhs);
// Accumulate impulses and clamp normal impulse (lambda[0]) to be non-negative
VecN oldLambda = cachedLambda;
cachedLambda[0] += lambda[0];
cachedLambda[0] = std::max(cachedLambda[0], 0.0f);
// Implement static friction
if (friction > 0.0f) {
// Calculate relative tangential velocity
Vec2 relativeVelocity = b->GetLinearVelocity() + Cross(b->GetAngularVelocity(), rb) -
a->GetLinearVelocity() - Cross(a->GetAngularVelocity(), ra);
Vec2 n = a->LocalSpaceToWorldSpace(normal);
Vec2 t = n.Normal(); // Tangent vector
float relVelAlongTangent = Dot(relativeVelocity, t);
// Desired friction impulse to cancel tangential velocity
float frictionImpulse = -relVelAlongTangent / (invM_tangent);
// Maximum allowable friction impulse (static friction limit)
float maxFrictionImpulse = cachedLambda[0] * friction;
// Clamp friction impulse within static friction limits
frictionImpulse = std::clamp(frictionImpulse, -maxFrictionImpulse, maxFrictionImpulse);
// Update total friction impulse
cachedLambda[1] += frictionImpulse;
// Update lambda[1] for applying impulses
lambda[1] = frictionImpulse;
}
// Apply the impulses to both bodies
VecN totalImpulse = Jt * lambda;
a->ApplyImpulseLinear(Vec2(totalImpulse[0], totalImpulse[1])); // A linear impulse
a->ApplyImpulseAngular(totalImpulse[2]); // A angular impulse
b->ApplyImpulseLinear(Vec2(totalImpulse[3], totalImpulse[4])); // B linear impulse
b->ApplyImpulseAngular(totalImpulse[5]); // B angular impulse
}
Explanation of the Changes:
-
Calculate Relative Tangential Velocity:
We compute the relative velocity at the contact point in the tangential direction. This helps us determine if the bodies are moving relative to each other along the surface.
-
Determine Desired Friction Impulse:
The goal is to compute the friction impulse necessary to reduce the relative tangential velocity to zero (simulate static friction). This involves dividing the negative relative tangential velocity by the effective mass in the tangential direction (invM_tangent), which you would need to compute based on your mass and inertia tensors.
-
Clamp Friction Impulse Within Static Friction Limits:
We ensure that the friction impulse doesn't exceed the maximum static friction force (maxFrictionImpulse). If it does, we clamp it, which means the bodies will start moving, and kinetic friction applies.
-
Update the Cached Lambda and Apply the Impulse:
We update cachedLambda[1] with the computed friction impulse and apply it to the bodies.
Additional Considerations:
-
Effective Mass in Tangential Direction (invM_tangent):
You'll need to compute the effective mass (invM_tangent) in the tangential direction, which depends on the masses and inertias of the bodies and their geometry relative to the contact point.
-
Numerical Thresholds:
Introduce a small threshold for velocities below which you consider the bodies to be at rest. This helps prevent numerical errors from causing unintended motion.
-
Separate Static and Kinetic Friction Coefficients:
Optionally, you might want to have separate coefficients for static and kinetic friction to simulate more realistic behavior.
Conclusion:
By modifying your friction model to properly handle static friction, you prevent small friction impulses from being incorrectly applied when objects are at rest, eliminating the trembling and unintended movement. Remember to ensure that all calculations involving floating-point numbers are handled carefully to minimize numerical errors.