Search Unity

Checking if a 2D collider is completely inside another 2D collider

Discussion in 'Scripting' started by matias-e, Sep 22, 2015.

  1. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Heya. I've searched on the web for a while, trying to solve how to check if a 2D box is completely inside another 2D box. I bumped into how to do it with 3D and have a faint idea on how to go about it with a PolygonCollider2D, both of which would probably be about circulating through the points in a for loop and checking if all of the points are inside the bounds of the other object.

    However, it seems like if I have a BoxCollider2D, I can't create an array from its points. Is there another way to do this? Perhaps I'm totally missing something. Thank you!
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    Why can't you create an array of the points?

    Do you mean that BoxCollider2D doesn't have a method or property that directly gives you an array of its points?

    That's because the BoxCollider2D doesn't store the extents of its collider as points. Instead they're calculated from the location of the transform, and the size property:
    http://docs.unity3d.com/ScriptReference/BoxCollider2D-size.html
     
  3. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Ah, ok! How would I go about turning the size property into an array? Sorry, I'm totally new to bounds!
     
  4. matias-e

    matias-e

    Joined:
    Sep 29, 2014
    Posts:
    106
    Alright, I solved the problem. What I did is that I calculated each corner verticle of the BoxCollider2D with some pretty simple math and then just ran it through a foreach loop. Here's the method:

    Code (CSharp):
    1. bool IsInside (BoxCollider2D enterableCollider, BoxCollider2D enteringCollider)
    2.     {
    3.         Bounds enterableBounds = enterableCollider.bounds;
    4.         Bounds enteringBounds = enteringCollider.bounds;
    5.  
    6.         Vector2 center = enteringBounds.center;
    7.         Vector2 extents = enteringBounds.extents;
    8.         Vector2[] enteringVerticles = new Vector2[4];
    9.  
    10.         enteringVerticles[0] = new Vector2 (center.x + extents.x, center.y + extents.y);
    11.         enteringVerticles[1] = new Vector2 (center.x - extents.x, center.y + extents.y);
    12.         enteringVerticles[2] = new Vector2 (center.x + extents.x, center.y - extents.y);
    13.         enteringVerticles[3] = new Vector2 (center.x - extents.x, center.y - extents.y);
    14.  
    15.         foreach(Vector2 verticle in enteringVerticles)
    16.         {
    17.             if(!enterableBounds.Contains(verticle))
    18.             {
    19.                 return false;
    20.             }
    21.         }
    22.         return true;
    23.     }