using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class MovingAI : MonoBehaviour {

    public float wanderRadius;
    public float senseRadius;
    public float sensePeriod;

    private Transform target;
    private NavMeshAgent agent;
    private float timer;

    private void Awake () {
        agent = this.GetComponent<NavMeshAgent>();
        timer = sensePeriod;
    }

    private void Update () {
        timer += Time.deltaTime;
        if (timer >= sensePeriod) {
            Vector3 newPos;
            if ((GameManager.Instance.GetPlayerPosition() - this.transform.position).magnitude <= senseRadius) {
                newPos = GameManager.Instance.GetPlayerPosition();
            }
            else {
                newPos = RandomNavSphere(transform.position, wanderRadius, -1);
            }
            agent.SetDestination(newPos);
            timer = 0;
        }
    }

    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;
    }

}
