# 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:

1. A spotlight that is parented to the enemy object acts as it's field of view.
2. 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.

• why not use a radar sensor? – Scalia Sep 23 '15 at 16:00
• @VincentScalia I am building a stealth game, and I would therefore like to simulate a somewhat realistic vision system, where the enemy reacts when the player gets in the field of view. Also, I'd like to keep the vision restricted by walls. – Droidge Sep 23 '15 at 16:08
• <img src="http://blend-exchange.giantcowfilms.com/embedImage.png?bid=521" /> try this .blend. I don't have time for an answer right now, but this is a radar sensor – Scalia Sep 23 '15 at 16:18
• why not a ray that roves back and forth with an animation really fast? – Scalia Sep 23 '15 at 17:24
• @VincentScalia How can I animate a ray? – Droidge Sep 24 '15 at 1:31

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


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.