简体   繁体   English

在CollisionEnter上平稳地将3D对象移动到另一个3D对象的表面

[英]Smooth moving a 3D Object to another 3D object's surface onCollisionEnter

Hi2.., HI2 ..,

I have a case: that I need to move a 3D object to smoothly move himself(eg using lerp) to another 3D object's surface on collision. 我有一个例子:我需要移动3D对象,以便在发生碰撞时将自己(例如使用lerp)平稳地移动到另一个3D对象的表面。

This is the script I use on detecting collision. 这是我用于检测碰撞的脚本。

public GameObject targetingObject;
private void OnCollisionEnter(Collision collision)
{

    Debug.Log("name: " + collision.gameObject.name);
    Debug.Log("tag: " + collision.gameObject.tag);

}

private void OnCollisionExit(Collision collision)
{
    targetingObject.transform.localPosition = new Vector3(0, 0, 0);
}

private void OnCollisionStay(Collision collision)
{
    Debug.Log("collision is staying");
}

This script work as It is and I am able to detect the collision when it happened. 该脚本按原样工作,发生碰撞时,我能够检测到碰撞。 However, I have a bit of difficulites to move the object to "attach" himself to a collided 3D object. 但是,我有点难以移动对象以将自己“附加”到碰撞的3D对象上。


Here is picture of the scenario. 这是方案的图片。 在此处输入图片说明


在此处输入图片说明


在此处输入图片说明

You can make achieve this by changing parent of green sphere to target object when the collision occurs. 您可以通过在发生碰撞时将绿色球体的父对象更改为目标对象来实现此目的。 Then green sphere will be attached to target and it can move together with its parent(aka target object). 然后,绿色球体将附着到目标,并且可以与其父对象(也称为目标对象)一起移动。 Here is the script for it: 这是它的脚本:

public GameObject Target;
public GameObject GreenSphere;

void Start () {

}

void Update () {

}
void OnCollisionEnter(Collision collision)
{       
    //Since you used Target as a public variable
    if(collision.gameObject == Target)
    {
        GreenSphere.transform.parent = Target.transform;
    }
}

Since op does not want to change parent of the object another approach can be calculating distance between spheres and once the distance is equal to target radius/ 2 + GreenSphere radius/2 , it means objects are touching each other and then they can be considered attached! 由于op不想更改对象的父对象,因此另一种方法是计算球体之间的距离,并且一旦该距离等于target radius/ 2 + GreenSphere radius/2 ,这意味着对象彼此接触,则可以认为它们已附着! . Here is the script for it: 这是它的脚本:

public GameObject target;
float targetSize;
float GreenObjSize;
void Start () {
    targetSize = target.transform.localScale.y / 2;
    GreenObjSize = gameObject.transform.localScale.y / 2;
    Debug.Log(targetSize);
}

void Update () {
    if((target.transform.position - gameObject.transform.position).magnitude > (targetSize + GreenObjSize))
    {
        gameObject.transform.position += Vector3.down * Time.deltaTime;
    }
}

This script must be attached to GreenSphere and will only work if objects are spheres! 该脚本必须附加到GreenSphere并且仅在对象是球体时才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM