So I have a few AIs walking between waypoints. What I want to accomplish here is to have my AI move to the waypoint, when he reaches it, he must stop, wait for a few seconds (Not walk just stand still), then move to the new waypoint. Lets pretend he was observing while at this point.
Issue right now - He moves to the waypoint with a twitchy behavior where he would usually avoid objects, sometimes gets stuck while moving to objects or its like the AI cant decide what to do, move or stand still. Without the Waitforseconds method the AI avoids objects perfectly.
Please note I want to use Coroutines for this even if you wouldn't use / recommend it for this. If you have a suggestion for using Unity's Random to decide when he stands still after reaching a point or not, that would be a bonus for me.
We define all fields and call the FSM() Coroutine with a default patrol state in the Start Method, from Here, This is my Code:
Update - Implemented A Boolean IsMoving variable - This works to some extent. The AI now moves perfectly to the waypoint. The Twitching however continues once the AI reaches the waypoint vicinity until he leaves the waypoint radius - The movement then continues to a normal state.
IEnumerator FSM()
{
while (alive)
{
switch (state)
{
case State.PATROL:
StartCoroutine(Patrol());
break;
case State.CHASE:
Chase ();
break;
default:
break;
}
yield return null;
}
}
/// <summary>
/// Patrol will move to a waypoint if too far, otherwise move to a next waypoint if one is reached.
/// </summary>
IEnumerator Patrol()
{
//Sets a common speed for the agent to move in.
agent.speed = patrolSpeed;
//Now we want to check the position the character is at vs the waypoint location - If i am too far, move closer
// My Position Waypoint Indexes - We Set Multiple
if (Vector3.Distance (this.transform.position, waypoints [wayPointIndex].transform.position) >= 2)
{
//Telling the navmesh agent where to go.
agent.SetDestination (waypoints [wayPointIndex].transform.position);
// false, false - Specifies if we are jumping or crouching
character.Move (agent.desiredVelocity, false, false);
}
//Now we want to check the position the character is at vs the waypoint location - If i am at a waypoint, move to a new index
else if (Vector3.Distance (this.transform.position, waypoints [wayPointIndex].transform.position) <= 2)
{
character.Move (Vector3.zero, false, false);
yield return new WaitForSecondsRealtime (6.0f);
wayPointIndex += 1; //Move towards a new waypoint in the waypoint indexes flags
//Move to a random waypoint
wayPointIndex = UnityEngine.Random.Range (0, waypoints.Length);
}
else
{
//Doesn't move, plays the idle movement - We know this point wont be reached but if so...
character.Move (Vector3.zero, false, false);
yield return null;
}
}