Search Unity

Getting some weird results from Collider2D.bounds.Contains()

Discussion in 'Scripting' started by VBenincasa, Sep 28, 2019.

  1. VBenincasa

    VBenincasa

    Joined:
    Feb 13, 2014
    Posts:
    12
    A certain check for bounds.Contains() was failing on me, so I decided to run some tests, and ultimately found something really weird.

    Here's the test code:

    Code (CSharp):
    1.     private void ContainsTest() {
    2.         Bounds myBounds = GetComponent<Collider2D>().bounds;
    3.         Debug.Log("Bounding box: " + myBounds);
    4.         //Is my own center inside my own bounding box?
    5.         if (myBounds.Contains(myBounds.center)) {
    6.             Debug.Log("My center is inside my bounding box!");
    7.         }
    8.         //What about another point that is exactly equal to my center?
    9.         Vector2 samePoint = new Vector2(myBounds.center.x, myBounds.center.y);
    10.         if (myBounds.Contains(samePoint)) {
    11.             Debug.Log("This point is also inside my bounding box!");
    12.         }
    13.         else {
    14.             Debug.Log("This point, that is exactly equal to my center, is somehow not inside my bounding box!");
    15.             if (samePoint.Equals(myBounds.center)) {
    16.                 Debug.Log("See, they ARE equal!");
    17.             }
    18.         }
    19.     }
    And this is the output:



    The Contains() is being passed two Vectors that are equal to each other (according to their Equals() function), but one returns "True" and the other returns "False".

    PS: Disregard the 0.0f for Y extents - I repeated the same test with a larger bounding box and the same issue happened.
     
    Last edited: Sep 29, 2019