Game Development Reference
of treasure, the goal location is a moving player. The NPC detects the player
within its field of vision using the vector between its position and the players.
This is calculated as
direction = player.position NPC.position;
The magnitude (length) of the direction vector represents the distance the
player is from the NPC. If the angle between the facing vector and direction
vector is less than the angle of vision and the magnitude of the direction
vector is less than the visible range, then the player will be detected
by the NPC.
The next workshop will demonstrate this in Unity.
Unity Hands On
Line of Sight AI
Step 1. Download Chapter Five/ChasingAI.zip from the Web site.
Open the chasingAI scene. In it you will find a large terrain and a
Step 2. Open the AI script with the script editor and add the code
shown in Listing 5.1 .
Listing 5.1 Basic Line of Sight Script
var target : Transform; //the enemy
private var seeRange = 100.0; //maximum attack distance -
//will attack if closer than
//this to the enemy
private var shootRange = 20.0;
private var keepDistance = 10.0; //closest distance to get to enemy
private var rotationSpeed = 5.0;
private var speed = 0.01;
private var state = "PATROL";
this.animation["shoot"].wrapMode = WrapMode.Loop;
this.animation["run"].wrapMode = WrapMode.Loop;
this.animation["idle"].wrapMode = WrapMode.Loop;
function Update ()
if (CanSeeTarget ())