Prevent collider from making a collision if another object is between the target

Hi all, I am not sure if this is even the right approach but I will try to explain what I am doing.

Basically, I am trying to create two systems of AI, Sight and Hearing. (I know I could use R.A.I.N, but I want to learn how to code!)

So, it makes sense in my head that hearing is a sphere collider that when something makes a sound (another collider from a target object) it will set the navmesh agent to move towards the sound.

Then, there is a cone shape collider in front of the model which represents sight, this will override hearing if the player is colliding with the sight collider.

Now, this all works fine, except that if an enemy is behind a building for example, but happens to be facing it, if the player walks behind the building it can collide with the sight collider, despite the fact that the enemy hasn’t actually got line of sight to the player.

So, is it even possible to prevent the sight collider from registering the player if an object is in the line of sight?

I thought that one approach might be the following workflow:

  1. Player collides with enemy sight collider
  2. Enemy detects the collision, but needs to check if it has line of sight
  3. Fires a raycast from the enemys face object to the position registered by the players hit
  4. if the only object hit by the raycast is the player then it must be able to see it
  5. If the hit is anything other than the player then ignore the hit

Now that makes sense, except that it only detects hit on enter or exit, so if the player is initially blocked by an object when it enters the collider, if it moves into line of sight without moving out of the collider the enemy wont actually notice as it only fired the raycast upon entry?

Sorry for the long post but I am trying to work out if this is the right approach or not, or whether I am making some fundamental noob mistake!!

Any help would be greatly appreciated :slight_smile:

I would keep the cone collider, then use raycasting in conjunction with it via OnTriggerStay() to determine if anything is blocking the line of sight to that object within the cone trigger area.
Like you are doing already but the OnTriggerStay() will continue the checks throughout the detection and avoid your enter/exit problem :slight_smile: