Implementing Line of Sight (LoS)

I started implementing Line of Sight (LoS) for my guard AI, to do this I have created a large sphere collider around each guard which will act as their viewing distance, the radius is currently set to 10, however this can be adjusted as necessary once the rest of the systems are implemented in terms of balancing.

To work out the view angle I am using Vector3.Angle where the "angle returned is the unsigned angle between the two vectors" (Docs.unity3d.com, 2018) where one vector is the direction between the player and the guard, and the other vector is the guard's forward vector.

I then send out a raycast to the player, this is to check if there are any obstructions such as a wall, however I was having trouble with this as when another guard's "view collider" was in the way, they could no longer see the player, which was an undesirable effect.  To try and diagnose the problem I used Debug.DrawRay to see where the problem was, however this still drew the ray to the player even if the "playerInSight" bool was set to true.  



The way I finally figured out that the problem was the other guards collider was the player had to be very close to the AI I was testing the sight on and doing a Debug.Log(other.collider.name) which was printing out the AI_Guard, however I thought this was hitting itself.  Until I positions the guards into different locations.


I then had to look into LayerMasks.  Originally I used this incorrectly, setting the Raycast to only find the player's layer, however this did work initially with the problem with the guards the enemies could now see the player through walls.  I then found a website (Holistic3d.com, 2018) that had a small tutorial on excluding layers from the raycast using bitshifting.  So now the raycast will ignore the other enemies while still being blocked by walls etc.



Reference List
[1] Docs.unity3d.com. (2018). Unity - Scripting API: Vector3.Angle. [online] Docs.unity3d.com. Available at:  https://docs.unity3d.com/ScriptReference/Vector3.Angle.html [Accessed 18 Nov 2018]
[2] Holistic3d.com. (2018). [online] Available at: https://holistic3d.com/news-tips/working-with-raycasts-and-layers-in-unity/ [Accessed 19 Nov. 2018]
[3] Answers.unity.com (2018). Raycast ignore layers except - Unity Answers. [online] Available at: https://answers.unity.com/questions/1164722/raycast-ignore-layers-except.html [Accessed 18 Nov 2018]
[4] Stack Overflow. (2018) How does the bitwise complement operator (~ tilde) work?. [online] Available at https://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-tilde-work