Game Development Reference
In-Depth Information
Having retrieved a list of all waypoints, the Patrol state can be coded, as shown in the
following code sample 7-6, which regularly selects waypoints as move new targets:
01 //--------------------------------------------------
02 //This coroutine runs when object is in patrol state
03 public IEnumerator State_Patrol()
04 {
05 //Set current state
06 CurrentState = AI_ENEMY_STATE.PATROL;
07
08 //Set Patrol State
09 ThisAnimator.SetTrigger((int) AI_ENEMY_STATE.PATROL);
10
11 //Pick a random waypoint
12 Transform RandomDest = WayPoints[Random.Range(0,
WayPoints.Length)];
13
14 //Go to destination
15 ThisAgent.SetDestination(RandomDest.position);
16
17 //Loop forever while in patrol state
18 while(CurrentState == AI_ENEMY_STATE.PATROL)
19 {
20 //Check if we can see player
21 if(CanSeePlayer)
22 {
23 //If we can see player, then chase to attack
24 StartCoroutine(State_Chase());
25 yield break;
26 }
27
28 //Check if we have reached destination
29 if(Vector3.Distance(ThisTransform.position,
RandomDest.position) <= DistEps)
30 {
31 //Reached destination. Changed state back to Idle
32 StartCoroutine(State_Idle());
33 yield break;
34 }
35
36 //Wait for next frame
37 yield return null;
38 }
39 }
40 //--------------------------------------------------
 
Search WWH ::




Custom Search