温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How do I keep child object from sliding away from parent as the parent moves?

c# - 当父母移动时,如何防止子对象滑离父母?

发布于 2020-03-31 23:03:30
 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);
     }
 }

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

查看更多

提问者
user12799900
被浏览
31
derHugo 2020-01-31 19:45

看来这Ball是一个Rigidbody

绝对不应嵌套多个Rigidbody或移动其父级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;
    }
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览