Game Development Reference
In-Depth Information
087 //Activates new state
088 switch(ActiveState)
089 {
090 case ENEMY_STATE.ATTACK:
091 StartCoroutine(AI_Attack());
092 SendMessage("Attack", SendMessageOptions.DontRequireReceiver);
//Notify Game Object
093 return;
094
095 case ENEMY_STATE.CHASE:
096 StartCoroutine(AI_Chase());
097 SendMessage("Chase", SendMessageOptions.DontRequireReceiver);
//Notify Game Object
098 return;
099
100 case ENEMY_STATE.PATROL:
101 StartCoroutine(AI_Patrol());
102 SendMessage("Patrol", SendMessageOptions.DontRequireReceiver);
//Notify Game Object
103 return;
104 }
105 }
106 //------------------------------------------------
107 //AI Function to handle patrol behaviour for enemy
108 //Can exit this state and enter chase
109 IEnumerator AI_Patrol()
110 {
111 //Stop Agent
112 Agent.Stop();
113
114 //Loop forever while in patrol state
115 while(ActiveState == ENEMY_STATE.PATROL)
116 {
117 //Get random destination on map
118 Vector3 randomPosition = Random.insideUnitSphere * PatrolDistance;
119
120 //Add as offset from current position
121 randomPosition += ThisTransform.position;
122
123 //Get nearest valid position
124 NavMeshHit hit;
125 NavMesh.SamplePosition(randomPosition, out hit, PatrolDistance, 1);
126
127 //Set destination
128 Agent.SetDestination(hit.position);
129
130 //Set distance range between object and destination to classify as 'arrived'
131 float ArrivalDistance = 2.0f;
132
133 //Set timeout before new path is generated (5 seconds)
134 float TimeOut = 5.0f;
135