centerOfMass unspected behaviour (Course Create with code 2)

Hello, I am doing the course “Create with code 2” and at the
Lesson 6.2 - Research and Troubleshooting, I should tray to make my car more stable by changing the center of mass with an empty child. I have assigned the position of the empty to the centerOfMass of the Rigidbody of my car. It should work but my cars now behave this way:

The center of mass is expressed in the rigidbody transform’s local space, as explained in the manual.

So make sure you’re not doing something along the lines of:

rigidbody.centerOfMass = child.transform.position;

but

// make sure to use local space position instead of world space position:
rigidbody.centerOfMass = child.transform.localPosition;
1 Like

A more correct way to assign the center of mass from an empty child would be:

// Convert world space position to rigidbody's local space position
rigidbody.centerOfMass = rigidbody.transform.InverseTransformPoint(child.transform.position);

Unless I’m missing something this behaves exactly the same as localPosition, only more verbose and less performant.

Only benefit would be it also works in cases where the transform is nested deep within the rigidbody hierarchy instead of being a direct child.

Exactly. Transform.localPosition refers to the local position of that object alone, but it doesn’t account for any other positions in the object’s hierarchy. Using InverseTransformPoint ensures it works in any case, not only when the CoM object is a direct child of the rigidbody’s transform (it may not be).

Performance is not a concern as the center of mass should be configured only once on start, or when it has changed explicitly. Changing CoM frequently is actually a performance issue, even when using localPosition, because 1) rigidbody inertia is recalculated, and 2) in vehicles, sprung masses are also recalculated.

1 Like

Thanks arkano22, it works now.

Thank you, Edy. Now I have something new to research :wink:

1 Like