void Idle() { if (idleTimer == 1.0f) { pathSize = 0; //Assign random target location while (pathSize < 3) { idleTarget = new Vector3(gameObject.transform.position.x + Random.Range(-150, 150), gameObject.transform.position.y + Random.Range(-150, 150), -10); //Keep looking for random target until it is a viable position while (pathGrid.GetNodeEmpty(idleTarget) == false) { idleTarget = new Vector3(gameObject.transform.position.x + Random.Range(-150, 150), gameObject.transform.position.y + Random.Range(-150, 150), -10); } //Find a path to the target location pathPosition = 0; pathFinder.FindPath(pathGrid, gameObject.transform.position, idleTarget); pathCompleted = false; pathSize = pathGrid.path.Count; } idleTimer -= Time.deltaTime; } else { //if the current path has came to an end if (pathCompleted) { //Reset the pathing variables pathSize = 0; idleTimer -= Time.deltaTime; //After idling is over, reset the timer to trigger a new path to be found if (idleTimer <= 0.0f) { idleTimer = 1.0f; return; } } //Once the path is completed, set it to complete if (pathPosition == pathSize - 2) { pathCompleted = true; return; } //iterate the path position once it has reached the next node in the path if (gameObject.transform.position == pathGrid.path[pathPosition].worldPos && pathPosition < pathSize - 1) { pathPosition++; } //While the path hasn't been completed if (pathPosition < pathSize - 2 && pathSize != 0) { //rotate towards this direction (determined by difficulty setting) //find the vector pointing from our position to the target Vector3 direction = (pathGrid.path[pathPosition].worldPos - transform.position); //rotate towards the way the agent is facing float rotation = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg; gameObject.transform.rotation = Quaternion.Slerp(gameObject.transform.rotation, Quaternion.Euler(0, 0, -rotation), 0.1f); //Prevent getting stuck on walls when idling //move gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, pathGrid.path[pathPosition].worldPos, 0.3f); //Reset path if stuck (position hasn't changed if (gameObject.transform.position == previousPosition) { idleTimer = 1.0f; return; } //record position for the next frame previousPosition = gameObject.transform.position; } } }