- Home /
Physics2D, weird layerMask behavior on Linecast, Raycast and OverlapPoint
Whenever I pass a value of 8 (custom LayerMask) to these functions, it collides with an object which uses the Default layer (which value is 0).
If I pass ~8, ~11 or ~13 for instance, they will collide with ~0 (anything that does not use the Default Layer)...
So I tried passing 0 as the layer mask, to check if it would correctly collide with the default layer, and surprisingly it didn't collide with anything.
The weird thing is that it works as expected in other scripts in the same scene. I'm trying to find out if it could be a conflict with some other code, but I haven't found a reasonable answer for this. Anyone has had the same problem?
Vector3 world$$anonymous$$ousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D[] hitInfos = Physics2D.RaycastAll(world$$anonymous$$ousePos, world$$anonymous$$ousePos, float.$$anonymous$$axValue, _hitLayer$$anonymous$$ask.value);
Collider2D collider = Physics2D.OverlapPoint(world$$anonymous$$ousePos, _hitLayer$$anonymous$$ask.value);
printing _hitLayer$$anonymous$$ask.value returns the correct layer value, however when I print the layer of the gameObject which is colliding I get a 0.
Answer by Keymax · Jul 17, 2014 at 02:03 PM
int layerID = LayerMask.NameToLayer(layerName); // 0-31
int layerMask = 1 << layerID; // 2^layerID
Collider2D[] hits = Physics2D.OverlapPointAll(worldPos, layerMask);
We all sometimes forget which out of the 10 kinds of people we are.
Answer by NoseKills · Jul 07, 2014 at 09:08 PM
I think this might be a bug.
With this code:
int layerToCheck;
Collider2D[] hits = new Collider2D[3];
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 p = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
int layerToCheck = LayerMask.NameToLayer("Default");
Debug.Log("Test 1");
int hitCount = Physics2D.OverlapPointNonAlloc(p, hits, layerToCheck);
while (hitCount-- > 0)
{
Debug.Log(" Test 1 HIT " + hits[hitCount].gameObject);
}
Debug.Log("Test 2");
hitCount = Physics2D.OverlapPointNonAlloc(p, hits);
while (hitCount-- > 0)
{
GameObject go = hits[hitCount].gameObject;
Debug.Log(" Test 2 HIT " + go + " Layer was: " + LayerMask.LayerToName(go.layer));
}
}
}
When clicking on the intersecting part of 2 2D colliders, the output is:
Test 1
Test 2
Test 2 HIT ColliderObject2 (UnityEngine.GameObject) Layer was: Default
Test 2 HIT ColliderObject1 (UnityEngine.GameObject) Layer was: Default
When checking for hits with the layermask int derived from "Default" we get 0 hits, but all hit objects retrieved with an unfiltered call have a layer of "Default"
Your answer
Follow this Question
Related Questions
Physics.Linecast seems to be hitting itself 1 Answer
Linecast and target visibility 1 Answer
Multiple raycasts in same fixedupdate 3 Answers
2D Raycast Layer Mask not working 1 Answer
How do I use layermasks? 9 Answers