Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Collision normal components always -1, 0 or +1

Discussion in 'Physics' started by iGoA, Nov 23, 2023.

  1. iGoA

    iGoA

    Joined:
    Aug 23, 2020
    Posts:
    22
    I don't know, what I am doing wrong here.
    I've a CircleCollider2d and some BoxCollider2d. I want the circle object to bounce/reflect, when it hits a box.
    For this purpose I read the contact normals like this:

    Code (CSharp):
    1. private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.         for(int i = 0; i < collision.contactCount; i++)
    4.         {
    5.             Debug.Log("collisssion: " + collision.GetContact(i).normal);
    6.         }
    7.     }
    When the circle hits the box in a slate angle, I'd expect the normal components to be some floating point values like (0.1248, -0.7733), but the result is always even values like (0,-1) or, when hitting the left, right or bottom box, (-1,0), (0,1),(1,0)
    upload_2023-11-23_12-1-7.png

    Why are the normal values always -1, 0 or 1?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,129
    Because contact normals are the surface normals (tangent to the surface) you hit. The box here has a surface normal of (0,-1) i.e. down.

    Note that you can also inspect the value of all contacts in the inspector in any Rigidbody2D or Collider2D you select. Just pause the game and use the inspector. Also, you can turn-on gizmos to draw those contact positions and normals too.
     
  3. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,477
    Because the normal of the collision is exactly that. The circle doesn't have an "angle": it always collides with its the closest point to the edge of the box. So the normal is given by the edges it collides to.

    Try rotating the box, then you'll see the normals rotated as well. It will always be the normal of the edge.
     
    iGoA likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,129
    If you're doing your own "bounce" then you reflect the previous velocity around that normal which gives you the outbound velocity.
     
    iGoA likes this.
  5. iGoA

    iGoA

    Joined:
    Aug 23, 2020
    Posts:
    22
    Thanks for you quick replies. Yes, the normals change to other values when I rotate the boxes. I didn't get it in the first place, but now it makes sense. :)
     
    Edy likes this.