Game Development Reference
In-Depth Information
//Function to return whether player can be seen right now
private bool HaveLineSightToPlayer(Transform Player)
{
//Get angle between enemy sight and player
float Angle = Mathf.Abs(Vector3.Angle(ThisTransform.forward,
(Player.position-ThisTransform.position).normalized));
//If angle is greater than field of view, we cannot see player
if(Angle > FieldOfView) return false;
//Check with raycast- make sure player is not on other side of
wall
if(Physics.Linecast(ThisTransform.position, Player.position,
SightMask)) return false;
//We can see player
return true;
}
As we saw in the earlier chapters, visibility is determined by a two-stage process.
First, the angle between the enemy look at vector and the normalized vector, which
points from the enemy to the player, decides the visibility. If the angle is less than
the enemy's field-of-view angle, then the player would be in front of the enemy and
they would be seen, provided no obstacles, such as walls, lie between the enemy and
the player. The second test, performed by Physics.Linecast , determines whether
an unbroken line can be drawn between the enemy and the player. If it can, then no
obstacle would exist between them and the player would be seen.
Creating the Chase state
If the player is seen by the enemy and is not within attacking distance, the enemy
would run to attack the player. This state, in which the enemy runs towards the
player with hostile intent, is the Chase state. There are two main exit conditions
for this state. If the enemy reaches attacking distance, they should change from the
Chase state to the Attack state. In contrast, if the player disappears from sight, the
enemy should continue to chase as best as they can for a while and then give up the
chase if, after an interval, the player still cannot be sighted. Refer to the following
code sample 7-9:
01 //This coroutine runs when object is in chase state
02 public IEnumerator State_Chase()
03 {
04 //Set current state
 
Search WWH ::




Custom Search