Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Collision.GetContact seems to give wrong values

Discussion in 'Physics' started by unity_EZj5DwOrncGVww, May 14, 2021.

  1. unity_EZj5DwOrncGVww


    May 14, 2021
    Hey all! Been trying to fix this for a while now, but haven't been able to find a solution

    I have a script that stops objects from moving downwards when they are touching the top of another object on the orange tetramino:
    Code (CSharp):
    1.     void OnCollisionStay2D(Collision2D collision)
    2.     {
    3.         if ( collision.gameObject.tag == "Ground" )
    4.         {
    5.             Vector2 direction = collision.GetContact(0).normal;
    6.             Debug.Log(direction.y);
    8.             if (direction.y == 1 )
    9.             {
    10.                 print("top");
    11.                 IsFalling = false;
    12.             }
    13.         else
    14.             {
    15.                   IsFalling = true;
    16.             }
    18.         }
    Having the objects like this SharedScreenshot.png in the scene from the start gives direction.y = 1 and stops the downward movement, but moving the orange tetramino to the exact same position with code gives
    direction.y = 0 and downwards movement is not stopped. Is there something wrong with my code or is it just a weird quirk of GetContact or something else entirely? Any help would be greatly appreciated!
  2. MelvMay


    Unity Technologies

    May 24, 2013
    Yes. You're expecting Y=1 always even though those shapes can contact anywhere. It seems you're focusing on what you want and not what migh be happening. For instance, why wouldn't there be a contact against the vertical edges where you might get a horizontal collision normal i.x. X != 0 and Y = 0?

    Go to "Project Settings > Physics 2D > Gizmos > Show Contacts" to turn on contact gizmos. Or pause the editor and look at the Rigidbody2D/Collider2D in the inspector and open the "Info > Contacts" roll-out to look at the contact count and details.

    Or even easier, use Debug.Log to verify your assumptions on what normals are there and how many contacts you're getting.

    The collider shape about is not convex so it's going to be made up of multiple convex shapes if this is a PolygonCollider2D. Each shape in a Collider2D can produce up to 2 contacts each (Circles only 1).