简体   繁体   中英

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

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.

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.


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! . 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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