Search code examples
c#unity-game-engineonmousedownmouse-position

Unity: collider2D.bounds.Contains not working properly


I've got a GameController object with a square 2D collider that covers the whole screen. Inside that GameController there are 7 objects (Zones), each one with their own polygon collider. Here's the setup:

View

Hierarchy

What I'm trying to do is to check if the clicked position is inside any of those Zone's colliders whenever I click inside the big square collider.

This is the OnMouseDown() code of the GameController's script:

void OnMouseDown ()
{
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    if(this.collider2D.bounds.Contains(mousePos)) Debug.Log ("1st Check");

    //'Zones' is a list with all the Zones GameObjects
    foreach (GameObject zone in Zones)
    {
        if(zone.collider2D.bounds.Contains(mousePos))
        {
            Debug.Log ("2nd Check");
        }
    }
}

Shouldn't I ALWAYS get the "1st Check"? Because it's redundant: if the OnMouseDown() got triggered because I clicked inside the collider, then the mouse position has to be inside the collider. But I never do, so I think I'm missing something right here about the Input.mousePosition or the ScreenToWorldPoint().


Solution

  • The problem was that .collider2D.bounds.Contains(mousePos) was getting a Vector3 but should've been receiving a Vector2. Changed it to .collider2D.bounds.Contains(Vector2(mousePos)) and works like charm.