Home > OS >  How to find which side of a collider has been hit
How to find which side of a collider has been hit

Time:01-09

Hi Guyz I could`nt Find a way How to find which side of a collider has been hit........ I have a car and its contain box collider...... And I want is when the other car hit my car then I will add some forces.... but first I need to detect which side of the car hit......

Hi Guyz I could`nt Find a way How to find which side of a collider has been hit........ I have a car and its contain box collider...... And I want is when the other car hit my car then I will add some forces.... but first I need to detect which side of the car hit......

CodePudding user response:

1 - You can loop through the contact points and check the normals.

void OnCollisionEnter(Collision collision)
{
    // Loop through all contact points
    foreach (ContactPoint contact in collision.contacts)
    {
        // Check the normal of each contact point
        if (contact.normal.y > 0)
        {
            // The top of the collider was hit
            Debug.Log("Top hit");
        }
        else if (contact.normal.y < 0)
        {
            // The bottom of the collider was hit
            Debug.Log("Bottom hit");
        }
        else if (contact.normal.x > 0)
        {
            // The right side of the collider was hit
            Debug.Log("Right hit");
        }
        else if (contact.normal.x < 0)
        {
            // The left side of the collider was hit
            Debug.Log("Left hit");
        }
    }
}

You can also use the zeroth index to check for the closest point instead of looping through all points.

2 - You can use the ClosestPoint of the collider.

3 - Check the direction

private void OnTriggerEnter (Collider other) {

     Vector3 direction = other.transform.position - transform.position;
     if (Vector3.Dot (transform.forward, direction) > 0) {
         print ("Back");
     } 
     if (Vector3.Dot (transform.forward, direction) < 0) {
         print ("Front");
     } 
     if (Vector3.Dot (transform.forward, direction) == 0) {
         print ("Side");
     }
}

CodePudding user response:

I solve it through this code

Oncollisionenter Vector3 dir = collision.tranform.position - transfrom.position; Getcomponent().AddForce(dir *50)

  • Related