Search code examples
c#unity-game-engineunity3d-2dtools

Unity Physics2D.OverlapBox always returns false


I'm trying to use Physics2D.OverlapBox to check if a collider is underneath the mouse when it's being clicked. OverlapArea and OverlapCircle works, but OverlapBox doesn't, and I'm not sure why!

Here's the code

void Update () {
    if (Input.GetButtonDown("Fire1"))
    {
        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = 10;
        Vector2 position = Camera.main.ScreenToWorldPoint(mousePosition);
        bool colliderHere = Physics2D.OverlapBox(mousePosition, new Vector2(3,3), 0, roomLayer);
        Debug.Log(position + " — " + colliderHere);
    }
}

I'm trying to use a box with a width and length of 3 units each, centered around the mouse position. This always returns false for some reason. Am I doing something wrong?


Solution

  • You're passing mousePosition instead of position to the OverlapBox method, that's why it doesn't work.

    Moreover, remember that OverlapBox will return null (and thus colliderHere = false) if you click on a collider which is a trigger IF the setting Queries Hit Triggers in the Physics 2D is off.