r/Unity2D•
MiniJar

Boxcollider 2D on enemy interfering with line of sight raycast?

Solved/Answered

Creating a topdown shooter and implementing AI that uses a line of sight system (i.e, if the enemy sees the player, the enemy will use MoveTowards to chase the player, if the player moves behind cover, it will do something else). I am having an issue with my raycast, as this line of sight is having weird dead spots and rarely works when the player is above the enemy. I've narrowed it down to the Boxcollider 2D on the enemy being the issue, as when I toggle it off, the raycast and methods work as intended.

None of the check boxes on the Boxcollider are checked, and the box collider fits around the enemy (a square) perfectly.

Here is my code for the line of sight

direction = (target.transform.position - this.transform.position).normalized;
RaycastHit2D playerhit = Physics2D.Raycast(transform.position, direction, (combatRadius + 6), 
(playerLayermask + obstacleLayermask));   //this should only be looking at colliders on the player and obstacle layers, the enemy is on neither layer
Debug.DrawRay(transform.position, direction, Color.green);
        if (playerhit.collider.gameObject.name.Equals("Player") && playerhit.collider != 
            playerhit.collider.gameObject.layer.Equals("Enemy"))
        {
            canSeeTarget = true;
            Debug.Log("I can see the target!");
        }

Here is my code for the chase

Debug.Log("CHASE MODE");

    transform.position = Vector2.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);

Any help would be greatly appreciated.

Posted Dec 30, 2021, 9:21 PM UTC · edited

14
EagleKneagle•

Have you tried putting the enemy on the IgnoreRaycast layer?

2
MiniJarOPIntermediate•

Just tried that, worked perfectly. Still experimenting with layers and trying to understand and utilize them. Thank you so much for the help!

2
EagleKneagle•

Nice! Glad it did the trick. Stuff like that can get really frustrating.

Happy coding!

2
melvmayProficient•

Don't use the addition operator (+) on masks though. If you want a combination of those bitmasks then use the bitwise OR operator i.e. "playerLayermask | obstacleLayermask"

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators

2