The collision response code is a follows:
// Collect all contacts from collision detection then solve them one by one List<Contact2D> contacts = detector.contact_List; // Iterate backwards through contacts so they can be removed from the list in the same loop for (int i = contacts.Count - 1; i >= 0; i--) { Contact2D contact = contacts; RigidBody2D a = contact.body[0]; RigidBody2D b = contact.body[1]; // Correct collision shape positions a.Shape.Position += contacts.normal * contacts.penetration; b.Shape.Position += -contacts.normal * contacts.penetration; // Coefficient of restitution float e = 0.9f; // BOING! // Calculate relative velocity Vector2 velocity_Relative = a.Velocity - b.Velocity; // Calculate scalar impulse float j = -(1f + e) * Vector2.Dot(velocity_Relative, contact.normal); // The following is not needed if normal is normalised (unit length): //j /= Vector2.Dot(contact.normal, contact.normal * (a.Mass_Inverse + b.Mass_Inverse)); // Calculate vector impulse Vector2 impulse = j * contact.normal; // Add impulse force at contact point for each body a.ApplyImpulse(impulse, contact.point); // Negate the force for the opposite body (Newton's Third Law) b.ApplyImpulse(-impulse, contact.point); // Remove this contact now that it has been resolved contacts.RemoveAt(i); }
The impulse is applied inside the body class as follows:
public void ApplyImpulse(Vector2 impulse, Vector2 point) { // v2 = v1 + j/m * n velocity_Linear += mass_Inverse * impulse; }
The only other aspect of collision response is at the end of the body's Integrate() method:
// Update the shape shape.Position = position; shape.Rotation = rotation;
Thanks again.