Warm tip: This article is reproduced from stackoverflow.com, please click
3d c# unity3d parent-child

How do I keep child object from sliding away from parent as the parent moves?

发布于 2020-03-31 22:52:06
 public GameObject Miffy;
 void OnTriggerEnter(Collider collider)
 {
     //when space key is pressed and collider is miffy(tagged Player)
     if (Input.GetKey(KeyCode.P) && collider.gameObject.tag == "Player")
     {
         Ball.transform.parent = Miffy.transform;

         Ball.transform.localPosition = new Vector3(0, 0, 0);
     }
 }
 private void Update()
 {
     //when key D is pressed miffy is no longer parent to ball object.
     if (Input.GetKeyDown(KeyCode.D))
     {
         Ball.transform.SetParent(null);
     }
 }

child object (Ball) increasing distance as parent(Miffy) object moves about.

Questioner
user12799900
Viewed
67
derHugo 2020-01-31 19:45

It seems that Ball is a Rigidbody.

You should not nest multiple Rigidbody or move a parent of a Rigidbody at all.


Rather use a FixedJoint.

Afaik you can simply do something like

private Rigidbody miffyRigidbody;
private FixedJoint BallFixedJoint;

void OnTriggerEnter(Collider collider)
{
    isColliding = true;
    if (collider.CompareTag("Player"))
    {
        miffyRigidbody = collider.attachedRigidbody;
    }
}

void OnTriggerExit(Collider collider)
{
    if (collider.CompareTag("Player"))
    {
        miffyRigidbody = null;
    }
}

private void Update()
{
    if(miffyRigidbody && Input.GetKeyDown(KeyCode.P))
    {
        if(!BallFixedJoint)
        {
            BallFixedJoint = Ball.GetComponent<FixedJoint>();
            if(!BallFixedJoint) BallFixedJoint = Ball.AddComponent<FixedJoint>();
        }

        BallFixedJoint.connectedBody = Miffy.GetComponent<Rigidbody>();
    }

    if(Input.GetKeyUp(KeyCode.P))
    {
        if(!BallFixedJoint)
        {
            BallFixedJoint = Ball.GetComponent<FixedJoint>();
            if(!BallFixedJoint) BallFixedJoint = Ball.AddComponent<FixedJoint>();
        }

        BallFixedJoint.connectedBody = null;
    }
}