Achieving 80 degreed line of sight using Vector3.Angle, and detecting if there is something in the way ?

Hello everybody, I’m writing some enemy cube AI and I’m kinda stuck somewhere. As everyone would wanted I wanted my AI to detect player if player is in detection range, also if AI is facing player, so we can sneak behind the AI. I achieved this by using Vector3.Angle, not raycasting directly because casting a ray from enemy’s forward to check player, was not a very flexible way. Everything works okay, but now I’m stuck about detecting if something is between AI and player, when using Vector3.Angle, see my code here :

var rayDirection = player.position - transform.position;

     if(Vector3.Angle(rayDirection, transform.forward) < angleToDetect);
       {
            // detection functions
       }

so as can be seen above, AI has a variable called angleToDetect which is 80 now, meaning the AI has a “cone” line of sight. But now how can I check if there is something between AI and player in this 80 degreed line of sight, if I use raycast, I can only use forward direction to check, and it will be very silly since I want my enemy to have cone line of sight. Any ideas about how to check if there is something on the 80 degreed line of sight between player and AI ?
Thanks :slight_smile:

You can use raycast or linecast, linecast is just easier.
Place an object at the level of the eyes of your AI guy (it makes more sense to see from the eyes than the position which is in the middle), then cast a line from this point to the player position (or an object attached to the player at head level)

if(!Physics.Linecast(eyes.position, playerHead.position, layer)){// You see each other}

Place the player and AI in the layer so that they are not considered in the method. This will allow the AI to see the player even though he is looking away from the AI.

EDIT: About layer:
First add a layer at Layer 8, call it LOS and assign your player and AI.
Now we need to consider all but this layer so in code:

// This set the bit 8 to 1
int layerMask = 1 << 8;
void Start(){
    // This inverts them all
    // bit 8 is now the only 0
    layerMask = ~layerMask;
}

void Update(){  
    if (!Physics.Linecast (eyes.position, eyePlayer.position, layerMask)) {
          // See the player
    }
}

More about this here: unitygems.com - unitygems Resources and Information.