Eye Sight for AI Characters

Hi All, I thought I will share the little eyesight script for AI Characters in the RPG game. It checks if the AI Character has the target in sight, in range and that nothing is blocking the view of the player.

It makes it possible for the player to sneak up on AI Characters and hide behind buildings and walls.

Check it out here on GitHub:

It’s my first time sharing code on GitHub, so sorry if I have made some mistakes. But I am keen to see if this helps anyone improve their game.



Thank you for sharing this!

Very well done!
Perception is, of course, an important element to a good AI.
There is one tweak I would make for optimization, I would move the angle check before the raycast check.

    private bool InSight(GameObject target) //Checks to see if the object seen is obstructed by another object and is with in range and angle.
        if (target == null) { return false; }
        RaycastHit hit;
        if ((target.transform.position - eyes.transform.position).sqrMagnitude >= seeingRange * seeingRange || !InSightAngle(target)) { return false; }
        return Physics.Linecast(eyes.transform.position, target.transform.position, out hit)  && hit.transform.gameObject.name == target.gameObject.name;

This causes the short circuit operations to go from least expensive to most expensive in clock cycles.
In effect, if the distance is too great, don’t check any further, then if the angle is wrong, don’t check any further, and then only do the raytrace after both these checks have passed.

Once again, well done!!

Thanks for the feedback.