- Home /
Raycast can't detect objects on layermask
I have two main layers being used in this particular part of my code - Player and StaticWorld.
During play, I try to run a raycast from the player to a location, and see if there's anything that would collide with that raycast in the StaticWorld layer.
If I use
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, clickDirection, clickDistance);
if (hit)
{
Debug.Log ("Hit on layer " + hit.transform.gameObject.layer + ", Target layer: " + LayerMask.NameToLayer("StaticWorld"));
}
Then when it hits objects in the StaticWorld layer, I get the message
"Hit on layer 8, Target layer: 8".
If I try to use
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position, clickDirection, clickDistance, LayerMask.NameToLayer("StaticWorld"));
if (hit)
{
Debug.Log ("hit on layer " + hit.transform.gameObject.layer + " Target layer: " + LayerMask.NameToLayer("StaticWorld"));
}
then I cease to get any raycast hits on the same objects from the same location. I've also tried using the static value 8 for the layermask with the same results. Am I missing something here?
Answer by YoungDeveloper · Apr 15, 2015 at 09:37 AM
Are you sure LayerMask.NameToLayer("StaticWorld") is correct? If you layer is with index 8, try this.
int mylayer = 1 << 8;
if(Physics2D.Raycast(gameObject.transform.position, clickDirection, clickDistance, mylayer){
Debug.Log ("hit");
}
To see what and where you are casting you can use ray debug.
Debug.DrawRay(gameObject.transform.position, clickDirection, Color.red);
I was using Debug.DrawRay previously just to make sure that the ray was actually there - I still have it, it's just outside the 'problem code." Shifting the layermask value seemed to do it - Does this mean that I should be doing (1 << Layer$$anonymous$$ask.NameToLayer(layerName))? Even setting a layermask variable seems like it should return 8 in this case.
I've never used Layer$$anonymous$$ask.NameToLayer(layerName), looks like too much for me. Use bit shifting 1 << 8 or simply declare public Layer$$anonymous$$ask layer;
and toggle what layers you want to cast from inspector.
Right, what I was asking there is how does declaring public Layer$$anonymous$$ask layer work when referencing it when gameObject.transform.layer is still spitting out 8 and the layer is actually 256 (1 << 8)?
It's 'spitting' out it's current active layer which has nothing to do with bit shifting 1 to position 8.
Here's a very good explanation of how it works on lowest level.
Your answer
Follow this Question
Related Questions
Is it possible to allow a raycast to pass through a collider to hit things behind it? 6 Answers
RaycastHit returns object without collider, in wrong layer 1 Answer
Using a raycast to get transform on specific layer 3 Answers
Raycast should ignore everything but player, yet still gets interrupted 1 Answer
How to create User layer that acts like the "Ignore Raycast" layer? 1 Answer