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:
Background
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)
{
...
}
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.
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.