- Home /
Physics2D.Linecast ignoring walls
In my current project all enemies cast a linecast towards the player, but even when there are walls between them the raycasthit2d.transform always returns the player transform anyway, why is this happening?
RaycastHit2D ray = Physics2D.Linecast(transform.position, player.transform.position, 9);
print(ray.collider);
if (ray.transform == player.transform)
{
print("in sight");
}
also: 9 is the layermask of the enemy so it doesn't return itself, also just found out that when you set the layermask to wall it always returns null
Answer by OfficerSugar · Jan 28, 2018 at 07:25 PM
So turns out the problem was my absolute misunderstanding of how layermasks work:
If you want a raycast (or in this case a linecast) to hit every layer except one you have to do this magic:
int layerMask =~ LayerMask.GetMask("Enemy");
Physics.Raycast(...,LayerMask);
I found this answer here: https://answers.unity.com/questions/1343414/ignore-one-layermask-question.html
Thanks to @oStaiko for indirectly answering my question!