Having some fun with scripts! Found out how to return to idle!

Hey Rick,

Really enjoying the class, learning a lot, trying to think of what I want in the future of this little demo/game, and really want bad guys to chase for a bit, attack, if you get away, they’ll return back to idle, so I kept poking around and feel pretty happy with it. If anyone else is curious, check out my code adjustments! Hopefully it’s not overboard!

public class EnemyAI : MonoBehaviour
{

    [SerializeField] Transform target;
    [SerializeField] float chaseRange = 15f;
    [SerializeField] float stopChaseRange = 20f;

    NavMeshAgent navMeshAgent;
    float distanceToTarget = Mathf.Infinity;
    bool isProvoked = false;

    // Start is called before the first frame update
    void Start()
    {
        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        CheckDistanceToTarget();   

        if(isProvoked)
        {
            EngageTarget();
        }

        else if(distanceToTarget <= chaseRange)
        {
            isProvoked = true;
        }
        else { ReturnToIdle(); }
    }

    void CheckDistanceToTarget()
    {
        distanceToTarget = Vector3.Distance(target.position, transform.position);
    }

    void EngageTarget()
    {
        if (distanceToTarget >= navMeshAgent.stoppingDistance)
        {
            ChaseTarget();   
        }
        else if (distanceToTarget <= navMeshAgent.stoppingDistance)
        {
            AttackTarget();
        } 
        else { ReturnToIdle(); }
    }

    void ChaseTarget()
    {
        GetComponent<Animator>().SetBool("attack", false);

        if (distanceToTarget >= stopChaseRange)
        {
            ReturnToIdle();
        }
        else
        {
            GetComponent<Animator>().SetTrigger("move");
            navMeshAgent.SetDestination(target.position);
        }
    }

    private void ReturnToIdle()
    {
        if (!navMeshAgent.hasPath)
        {
            GetComponent<Animator>().SetTrigger("idle");
        }
        isProvoked = false;
    }

    void AttackTarget()
    {
        GetComponent<Animator>().SetBool("attack", true);
        Debug.Log("Zombie Bites You!");
    }

    void OnDrawGizmosSelected()
    {
        // Display the explosion radius when selected
        Gizmos.color = Color.red;        
        Gizmos.DrawWireSphere(transform.position, chaseRange);
    }
}

Privacy & Terms