- Home /
Why is Raycast ignoring the layer mask?
So, in my 2D game, I have this laser that the player shoots, right? I'm trying to make it so it doesn't go through walls. I got that working, but now it doesn't go through objects that it's supposed to go through. The walls are on layer "Ground", and the other objects are on other various layers. The obvious solution was to create a layer mask, but alas, it still doesn't work. Can anyone help me figure out what's wrong with my code?
hit = Physics2D.Raycast(transform.position, Vector2.right, 1 << LayerMask.NameToLayer("Ground"));
if(hit.distance > maxDistance)
{
laserPos = Vector2(transform.position.x + maxDistance, transform.position.y);
} else {
laserPos = hit.point;
}
Answer by siaran · Feb 25, 2015 at 12:24 PM
I'm really terrible with that << thing to get layermasks to work properly I always get confused on what values to use and if I should put a ~ somewhere - but luckily, you don't have to!
Instead, I generally do something like
public LayerMask mask;
hit = Physics2D.Raycast(transform.position, Vector2.right, mask);
if(hit.distance > maxDistance)
{
laserPos = Vector2(transform.position.x + maxDistance, transform.position.y);
} else {
laserPos = hit.point;
}
and you just set what layers you want to mask in the editor.
Your answer
