【问题标题】:"Stick" gameObject to another gameObject after collision?碰撞后将游戏对象“粘”到另一个游戏对象?
【发布时间】:2015-10-31 16:34:50
【问题描述】:

目前,我正在使用以下代码使对象粘在其他游戏对象上:

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;
    gameObject.transform.SetParent (col.gameObject.transform);
}

它运行良好,但它会导致许多其他问题。例如,碰撞后,它就无法再检测到碰撞。

是否有人拥有此代码的替代方案(这使得游戏对象在碰撞后粘在另一个游戏对象上)?

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    这是你的一个开始,请注意这不考虑轮换,我相信你能弄清楚,对吧? ;)

    protected Transform stuckTo = null;
    protected Vector3 offset = Vector3.zero;
    
    public void LateUpdate()
    {
        if (stuckTo != null)
            transform.position = stuckTo.position - offset;
    }
    
    void OnCollisionEnter(Collision col)
    {
        rb = GetComponent<Rigidbody>();
        rb.isKinematic = true;
    
        if(stuckTo == null 
            || stuckTo != col.gameObject.transform)
            offset = col.gameObject.transform.position - transform.position;
    
        stuckTo = col.gameObject.transform;
    
    }
    

    编辑:正如所承诺的,这是一个考虑轮换的更高级版本:

    Transform stuckTo;
    Quaternion offset;
    Quaternion look;
    float distance;
    
    public void LateUpdate()
    {
        if (stuckTo != null)
        {
            Vector3 dir = offset * stuckTo.forward;
            transform.position = stuckTo.position - (dir * distance);
            transform.rotation = stuckTo.rotation * look;
        }
    }
    
    void OnCollisionEnter(Collision col)
    {
        rb = GetComponent<Rigidbody>();
        rb.isKinematic = true;
    
        if(stuckTo == null 
            || stuckTo != col.gameObject.transform)
        {
            Vector3 diff = col.gameObject.transform.position - transform.position;
            offset = Quaternion.FromToRotation (col.gameObject.transform.forward, diff.normalized);
            look = Quaternion.FromToRotation (col.gameObject.transform.forward, transform.forward);
            distance = diff.magnitude;
            stuckTo = col.gameObject.transform;
        }
    }
    

    【讨论】:

    • 我收到error CS0019: Operator `-' cannot be applied to operands of type `UnityEngine.Transform' and `UnityEngine.Vector3'
    • 在线offset = col.gameObject.transform - transform.position;
    • 我认为你需要检查你的代码,因为当我运行我的游戏时,gameObject 就消失了。
    • 这是因为 LateUpdate() 方法:public void LateUpdate() { if (stuckTo != null) transform.position = stuckTo.position + offset; }
    • Debug.Log(transform.position); 写入 if 语句后的 transform.position = stuckTo.position + offset; 行并告诉我它在说什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多