using UnityEngine; using UnityEngine.AI; public class WanderingAIWaypointsOld : MonoBehaviour { public Transform[] waypoints; public float wanderTimer; public float targetScattering = 5.0f; //Streuung private Animator anim; private NavMeshAgent agent; private float timer; private int prevWP = -1; private Vector3 target; // Use this for initialization void Start() { agent = this.GetComponent(); anim = this.GetComponent(); anim.SetBool("isWalking", false); anim.SetBool("isIdle", true); timer = wanderTimer; } private void FixedUpdate() { timer += Time.deltaTime; if (timer >= wanderTimer) { if (waypoints.Length == 0) return; int currentWP = Random.Range(0, waypoints.Length); // Until previous and current WP are no longer the same, otherwise double waiting time for same WP while(prevWP == currentWP) currentWP = Random.Range(0, waypoints.Length); prevWP = currentWP; target = checkTarget(waypoints[currentWP].transform.position, targetScattering); if(target.x != float.PositiveInfinity) { if (agent.isActiveAndEnabled) agent.SetDestination(target); anim.SetBool("isWalking", true); anim.SetBool("isIdle", false); timer = 0; } else { timer = wanderTimer; } } else { // if x and z coordinates of newPos are the same as the position, humans reached destination and idle animation can start if (target.x == transform.position.x && target.z == transform.position.z) { anim.SetBool("isWalking", false); anim.SetBool("isIdle", true); } } } public static Vector3 checkTarget(Vector3 target, float dist) { Vector3 modifiedTarget = Random.insideUnitSphere * dist + target; // SamplePosition also checks the y axis. However, this is not relevant for me, so valid positions (x & z) are also discarded. // -3.6f is the only valid entry for y modifiedTarget = new Vector3(modifiedTarget.x, 0f, modifiedTarget.z); NavMeshHit navHit; NavMesh.SamplePosition(modifiedTarget, out navHit, 1.0f, -1); return navHit.position; } }