Physics2D.OverlapPoint mystery

Hello All,

Of course, may not a mystery - and experienced persons may can help to me - but a strange issue has just appeared while I trying 2D features.

I’ have two different sprites, background and a Wall.
Background sprite renderer has -1 as order in layer, Wall has 0.

I would like to detect Wall with mouse press, and sometimes it’s okay, but sometimes Physics2D.OverlapPoint detect Background sprite first, but fo course it looks behind the Wall in the scene.

I tried to find out, what’s happening with Physics2D.OverlapPointAll, and seems, in some cases order of detection has changed, like:

  1. Background
  2. Wall

Does anybody experienced similar issue, or what I’m doing wrong?

The code for detect the overlapping is:

Vector3 wp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var touchPos = new Vector2(wp.x, wp.y);
          
Collider2D hit = Physics2D.OverlapPoint(touchPos);

if (hit != null)
{
    ...
}

Thank you for your help!

Physics is completely decoupled from sprites, it knows nothing about rendering thus it’s not related to rendering orders etc.

The ray/line/shape casts are order by distance and the overlap checks are ordered by Z order of the transform. The only reason the Z order of the transform is used is that the overlap checks allow you to select a Z range for the query. If the Z is the same then the order is undefined.

When you use the overlap calls that only return a single collider then you’ll only get the first one in the list using the sorting rules above i.e. the lowest Z or undefined.

1 Like

Thank you for the explanation, I understand now, and the problem has fixed.

You’re most welcome, glad I could help.

Sorry for reviving such an old question, but I need to know what the line:

Collider2D hit = Physics2D.OverlapPoint (v2TouchedPos)

actually does. I mean, “hit” can never be null in a real game, right? You are always going to click/touch into something that does exist.

I’m asking this because in a “shooting” method that I’ve come across, I’ve seen a line that says “if (hit != null) …”. It’s never going to be null, right?

If you read the documentation, it tells you that it returns NULL if no collider was found. The return type is Collider2D which is a reference type which can be NULL.

My fault, I thought that method would detect whatever gameObject.

One more related question MelvMay: using the Physics2D.Raycast method, I’ve come across with an argument that says:

1 << LayerMask.NameToLayer ("soldier")

What can this mean?

If you click on the code you posted it takes you to the documentation. Here’s the documentation for layers.

It means the Raycast will only consider Colliders belonging to a Layer called “soldier”. It will ignore all other Colliders in its path.
http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html