碰撞后将游戏对象“粘贴”到另一个游戏对象?

时间:2015-10-28 16:53:23

标签: c# unity3d unity5

目前,我使用以下代码使对象坚持其他游戏对象:

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

它完美无缺,但它会导致许多其他问题。例如,在碰撞之后,它不再能够检测到碰撞。

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

1 个答案:

答案 0 :(得分:0)

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

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