Rigidbody.CenterOfMass seems to return wrong values for me.
here a simpified scene:
what you see here:
Black ray: Center of the box collider (should be center off mass)
Red ray: what Rigidbody.CenterOfMass returns
Cyan ray: center of the gameObject
the box is imported from blender (that it is off center is intentional)
and when im already here, how do i get the center of mass from multiple rigidbodys connected with joints from unity?
Does the single box has a rigidbody? Or are the two boxes part of a single rigidbody? If they are childs of a rigidbody they count as compound colliders and the center of mass would be calculated accordingly.
Two rigidbodies don’t have a common center of mass. Each rigidbody is calulated on it’s own. Joints just apply forces between the two bodies.
We don’t have enough information to give a clear answer. It’s not clear what belongs to the same object and what’s a seperate object.
Keep in mind that rigidbodies in rigidbody physics are considered “rigid”, so they don’t change shape or size dynamically. All physical properties of the rigidbody stays constant.
Also we don’t know how you visualized the center of mass. Rigidbody.centerOfMass is a local vector but it isn’t defined in localspace as it isn’t affected by scale. To get the worldspace position of the center of mass you have to do:
var c = transform.position + transform.rotation*rb.centerOfMass;
or
var c = transform.position + transform.TransformDirection(rb.centerOfMass);
TransformPoint will not give the right position as it applies the scale of the object as well.
The documentation reads as follows:
Note: centerOfMass is relative to the
transform’s position and rotation, but
will not reflect the transform’s
scale!
private void OnDrawGizmos() { getCenterOfMass (); Gizmos.color = Color.red; Gizmos.DrawWireSphere(centerOfMass, 0.2f); } } You can cache result for frame or longer time for better performance.