首页 > 解决方案 > 当父对象移动时,如何防止子对象滑离父对象?

问题描述

 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);
     }
 }

子对象(球)随着父对象(Miffy)的移动而增加距离。

标签: c#unity3d3dparent-child

解决方案


似乎Ball是一个Rigidbody.

您根本应该嵌套多个Rigidbody或移动 a 的父级Rigidbody


而是使用FixedJoint.

Afaik 你可以简单地做类似的事情

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;
    }
}

推荐阅读