How to set center of gravity on prefab child?

Viewed 1489

I have a 3d model prefab in unity that I'm trying to add physics to. The issue is that the prefab was imported from auto desk and when that happened the pivot/center of gravity for all the child mesh objects was not where you would necessarily expect them. I've tried attaching a rigid body to the various child objects and setting the center of mass with a script but it doesn't seem to be working as I would expect. My method for setting the center of mass involved creating two child game objects at either end of the highlighted object and using the midpoint formula to a 'good enough' center of mass. Is there any way around this beyond rebuilding/re-importing the object?

Showing the off center pivot

Showing the weird center of mass

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CenterOfGravity : MonoBehaviour
{
    // Start is called before the first frame update
    public Transform[] centerPoints;
    public Rigidbody rb;
    void Start()
    {
        centerPoints = gameObject.GetComponentsInChildren<Transform>();


        Transform center1 = Array.Find(centerPoints, elem => elem.name.Equals("Center1"));
        Transform center2 = Array.Find(centerPoints, elem => elem.name.Equals("Center2"));


        Vector3 center = (center1.localPosition + center2.localPosition)/2.0f;

        rb = GetComponent<Rigidbody>();
        rb.ResetCenterOfMass();
        rb.centerOfMass = center;

    }

    // Update is called once per frame
    void Update(){}
}
2 Answers

Every time I have to change the center off mass of an object, I create an empty child Game Object in the place where I want to be the center of mass.

After that, I set the center off mass of the object, to the local position of the new child object, something like that:

    public GameObject childObj, myObj;

    void Start()
    {
      myObj.GetComponent<Rigidbody>().centerOfMass = childObj.transform.localPosition;
    }

Edit:

If you want to change the pivot of a GameObject, you need to do those things:

1-Create an empty game object and name it as "Pivot".

2-Place the pivot where you want the center of mass to be.

3-Asign your initial game object that you want to change the pivot as child of your new object called "Pivot".

Now the pivot of the initial game object should be the empty game object called pivot.

Some disclaimers first, AFAIK there's no way to do that in unity BUT! there is a workaround I came across when I had a similar issue. The thing is that I'm not quite sure what your work pipeline is, and this fix might be even worst than just modifying the meshes in auto desk and reimporting it.

The idea is to move your object temporarily to another game object, then modifying the broken pivot and bringing it back to the original object. The idea comes from this video. It may work for you too!

Related