“棒"碰撞后游戏对象到另一个游戏对象? [英] "Stick" gameObject to another gameObject after collision?

查看:29
本文介绍了“棒"碰撞后游戏对象到另一个游戏对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently, I am using the following code to make objects stick to other gameObjects:

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

它运行良好,但会导致许多其他问题.例如,在碰撞后,它不能再检测到碰撞.

It works perfectly, but it causes many other problems. For example, after colliding, it can no longer detect collisions.

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

Does someone possess an alternative to this code (which makes a gameObject stick to another one after collision)?

推荐答案

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

Here's a start for you, please note that this does not take into account rotation, that i'm sure you will be able to figure out, right? ;)

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;

}

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

As promised, here is a more advanced version taking rotation into account:

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

这篇关于“棒"碰撞后游戏对象到另一个游戏对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆