-3

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

derHugo
  • 83,094
  • 9
  • 75
  • 115
Mr. Gamer
  • 1
  • 2

2 Answers2

0

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");
     }
}
Çağatay IŞIK
  • 937
  • 6
  • 17
0

I solve it through this code

   Oncollisionenter
   Vector3 dir = collision.tranform.position - transfrom.position;
   Getcomponent<RigidBody>().AddForce(dir *50)
COvayurt
  • 827
  • 2
  • 11
  • 36
Mr. Gamer
  • 1
  • 2