Guard AI Idle times

Guard AI part 3

In this article we will let the guard idle a bit at the end of his patrol route.

Initialization and Start()

We will be using a coroutine to wait to update the next destination. To prevent the code to update the destination we added a bool variable to know whether the target is reached or not.

private NavMeshAgent _agent;
public List<Transform> waypoints;

private int currentTarget = 0;
private bool _isReverse = false;
private bool _targetReached;

private float _waitToMoveMin = 2f;
private float _waitToMoveMax = 5f;

void Start ()
{
_agent = GetComponent<NavMeshAgent>();
}

Update()

First we check if there are waypoints set or not. This is so the same script can be used on waypointless guards.
Next we will check the distance to the target to see if it has reached it or not.
Targetreached will be set to true so this part of code won’t be called until we updated our destination and set it to false again.
In this part of code we also check is the waypoint is the first or last one. Reverse will be set to true or false accordingly and in these cases we want our guard to wait a bit before moving again. Thus we start our coroutine.
When the currenttarget is neither the first or the last we just change our waypoint.

void Update ()
{
if (waypoints.Count > 0 && waypoints[currentTarget] != null)
{

float distance = Vector3.Distance(transform.position, waypoints[currentTarget].position);
if (distance < 1 && _targetReached == false)
{
_targetReached = true;

if (currentTarget >= waypoints.Count - 1)
{
_isReverse = true;
StartCoroutine(WaitBeforeMoving());
}
else if (currentTarget <= 0)
{
_isReverse = false;
StartCoroutine(WaitBeforeMoving());
}
else
{
ChangeWaypoint();
}
}
_agent.SetDestination(waypoints[currentTarget].position);
}
}

Coroutine Wait before moving

Wait a random few seconds and then change the waypoint.

IEnumerator WaitBeforeMoving()
{
yield return new WaitForSeconds(Random.Range(_waitToMoveMin, _waitToMoveMax));
ChangeWaypoint();
}

ChangeWaypoint()

In this function we set our targetreached to false again so we will check the distance to our destination again. At the same time we also update our next waypoint.

void ChangeWaypoint()
{
_targetReached = false;

if (_isReverse == true)
{
currentTarget--;
}
else if (_isReverse == false)
{
currentTarget++;
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tristan Engel

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.