Find line of sight

Has anyone done any work on a script where an NPC attempts to find out where to stand in order to have line of sight on an enemy?

I am about to start work on this but it seems like a feature that most people would need if dealing with ranged combat. In the illustration below I show that I need a script where the npc works out the position he needs to be standing in the get LOS on the enemy and then walks there. any ideas before I fumble my way through it?


if own['Target']!="Empty":
   
   
   ray= rayCastTo(own['Target'].worldPosition, 0,'Enemy')

   if ray!=None:
      ## I see him
   else:
      ## try 15 times Find point in nav mesh @ height where raycast is positive ? if you can't then just try and navigate to enemy?
       

Probably the easiest and most efficient way would be to mark any openings in obstructions when you’re creating the level/objects (e.g. parent an Empty to the object, place it in the window, and add it to a list). Then you can have the AI navigate towards the nearest opening when you detect its line of sight is blocked by that obstruction. If you want the AI to move to a location away from the window like you’ve draw in your picture, you can just pick a point on the line defined by the vector from the target to the opening marker.

This opens up some more interesting possibilities as well. For example, if a wall has multiple openings like a window and a doorway, you can give the openings different weights based on how much cover they provide and have the AI favor openings with more cover.

If the obstacle doesn’t have any openings, then I would just have the AI navigate towards the target and continue ray casting until it can see the target or the ray hits an obstacle that has an opening.

Thanks for the heads up guys. I realized some of my code was fighting itself. Now I just gave the npc steer towards the enemy until it gets into melee range unless it gets LOS. In which case it will stop and fire until it loses LOS. Thanks for the inspiration