BGE: Create a sight system for an enemy What I want to do here is create a system where an enemy object has some kind of "sight", as in the enemy can detect a player object when the player object comes in its field of view. I am currently thinking of the following two ways:


A spotlight that is parented to the enemy object acts as it's field of view.
The enemy object casts multiple rays, with each ray being 5 degrees away from the previous one, creating an isosceles triangle of some sorts with rays between it.


The first method is problematic, and I do not know how to go about with the second method. How can I go about implementing it? Also, is there another way of doing the same that is better than the two methods listed above? If so, please do mention it.
Because the radar sensor finds all objects within its distance cone, it will return all objects, even ones hidden behind others.
To find only the "visible" objects, I'm checking that a ray can go from the radar object (the object with the Radar sensor logic) to each of the detected objects with rayCastTo.

This script loops through all the objects that the Radar sensor detects, and casts a ray to each of the objects. (Think of it as shining a laser   towards each of the detected objects, if the laser hits the object then the radar object can see it, if some other object is in the way, then it is blocked and it is hidden.)

import bge

cont = bge.logic.getCurrentController()
own = cont.owner

radar = cont.sensors["Radar"]

for obj in radar.hitObjectList:
    if obj is own.rayCastTo(obj, radar.distance):
        print(obj)


Line 9 is where the magic happens: own.rayCastTo(obj, radar.distance):.
That function starts the ray at the radar object, own. Then the first argument obj is the object that the ray is pointing towards. The last argument radar.distance is how long the ray will be, here I am using the distance set in the radar sensor, so the two will always be the same length.

All you need to do is connect this script to a Radar Sensor as shown below.