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

1 Answer

1

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: Ignore one layermask question - Questions & Answers - Unity Discussions

Thanks to @oStaiko for indirectly answering my question!