Physics2D.OverlapCircle problem

Hi guys, I’m working on a 2D game and am trying to work on a problem of moving a 2D object with transform.position. What I’m trying to do is move an object with mouse click and drag, and moving said object by altering its transform. What I want is to make sure that on release, the object isn’t lying on another object, so I thought the best way to check would be with Physics2D.OverlapCircle(mouse release point, object radius), but that clearly doesn’t work because the said gameObject is in that area. Is there any way to get the function to ignore specific gameObject, or is there some better way? Any help would be appreciated. Thanks!

Here’s a bit of my code for reference:

Vector3 currPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Vector2 curr2DPos = newVector2 (currPos.x, currPos.y);

if (Physics2D.OverlapCircle (curr2DPos, radius)) {
transform.position = startPos;
} else …

When you’re using Physics2D.OverlapCircle, you can also include a layerMask as the third parameter (Unity - Scripting API: Physics2D.OverlapCircle). You can use that layerMask to check for overlap with colliders on the layer you want. As long as the object that you’re moving isn’t on a layer in the layerMask, your script won’t be triggered by that GameObject.

1 Like

Using the layer-mask above is the best method but you can and probably do want to check for all colliders overlapping the circle?

If that’s the case then use either Physics2D.OverlapCircleAll or the non-allocating Physics2D.OverlapCircleNonAlloc.

3 Likes

thanks guys!