The char. is patrolling waypoints. At each waypoint he will stop and an animation will play. If you click on the Char. he will run to another set of waypoints. The issue is, while the Char. is stopped at the waypoint, if you click on him, he wont run. He should run at anytime he is clicked on. Navmesh and mecanim is being used.
void OnMouseDown()
{
isClicked = true;
StartCoroutine(WaitForSomeTime());
Vector3 markerPos = markers[Random.Range(0, markers.Length)].transform.position;
GetComponent<NavMeshAgent>().destination = markerPos;
posToCheck = markerPos;
canCheckDistance = true;
}
void Update ()
{
if (isClicked) {
Running ();
} else {
if (!isClicked)
Patrolling ();
}
}
void Running ()
{
nav.speed = runSpeed;
if (canCheckDistance) {
if (Vector3.Distance (transform.position, posToCheck) > distanceLimit - 0.5f) {
isClicked = false;
canCheckDistance = false;
}
}
}
void Patrolling ()
{
// Set an appropriate speed for the NavMeshAgent.
nav.speed = patrolSpeed;
// If near the next waypoint or there is no destination...
if(nav.remainingDistance < nav.stoppingDistance || waitTimeSet)
{
if(!waitTimeSet)
{
patrolWaitTime = Random.Range(2,4);
anim.SetBool(patrolWayPoints[wayPointIndex].name, true);
//Debug.Log (patrolWayPoints[wayPointIndex].name);
patrolTimer = 0;
waitTimeSet = true;
}
// ... increment the timer.
patrolTimer += Time.deltaTime;
//Debug.Log (patrolTimer);
// If the timer exceeds the wait time...
if(patrolTimer >= patrolWaitTime)
{
anim.SetBool(patrolWayPoints[wayPointIndex].name, false);
if(wayPointIndex != null)
lastPoint = wayPointIndex;
wayPointIndex = Random.Range(0, patrolWayPoints.Length);
//Debug.Log ("before last = " + lastPoint + " new = " + wayPointIndex);
if(lastPoint == wayPointIndex)
{
int[] tempIntArray = new int[patrolWayPoints.Length - 1];
int cnt = 0;
for (int i = 0; i < patrolWayPoints.Length; i++)
{
if(i != lastPoint)
{
tempIntArray[cnt] = i;
cnt ++;
}
wayPointIndex = tempIntArray[Random.Range (0,tempIntArray.Length)];
}
//Debug.Log ("after last = " + lastPoint + " new = " + wayPointIndex);
}
nav.destination = patrolWayPoints[wayPointIndex].position;
waitTimeSet = false;
}
}
else
{
patrolTimer = 0;
}
}
IEnumerator WaitForSomeTime()
{
waitTime = Random.Range(4,31);
yield return new WaitForSeconds(waitTime);
isClicked = false;
}
}