1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using UnityEngine;
- using UnityEngine.AI;
- public class WanderingAIOld : MonoBehaviour
- {
- public float wanderRadius;
- public float wanderTimer;
- private Animator anim;
- private NavMeshAgent agent;
- private float timer;
- private Vector3 newPos;
- // Use this for initialization
- void Start()
- {
- agent = this.GetComponent<NavMeshAgent>();
- anim = this.GetComponent<Animator>();
- anim.SetBool("isWalking", false);
- anim.SetBool("isIdle", true);
- newPos = RandomNavSphere(transform.position, wanderRadius, -1);
- timer = wanderTimer;
- }
- // Update is called once per frame
- void Update()
- {
- timer += Time.deltaTime;
- //Debug.Log("Pos: "+ transform.position);
- if (timer >= wanderTimer)
- {
- // generating random destination position
- newPos = RandomNavSphere(transform.position, wanderRadius, -1);
- if(agent.isActiveAndEnabled)
- agent.SetDestination(newPos);
- anim.SetBool("isWalking", true);
- anim.SetBool("isIdle", false);
- timer = 0;
- } else
- {
- // if x and z coordinates of newPos are the same as the position, humans reached destination and idle animation can start
- if (newPos.x == transform.position.x && newPos.z == transform.position.z)
- {
- anim.SetBool("isWalking", false);
- anim.SetBool("isIdle", true);
- }
- }
- }
- public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
- {
- Vector3 randDirection = Random.insideUnitSphere * dist;
- randDirection += origin;
- NavMeshHit navHit;
- NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
- return navHit.position;
- }
- }
|