using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UIElements;

public class MonsterController : MonoBehaviour
{
    private Transform monsterTr;
    private Transform playerTr;
    private NavMeshAgent agent;
    private Animator animator;

    public enum State { 
        Idle,
        Trace,
        Attack,
        Die
    }
    public State state = State.Idle;
    public float tranceDist = 10.0f;
    public float attckDist = 2.0f;
    public bool isDie = false;


    public 
    void Start()
    {
        animator = GetComponent<Animator>();
        monsterTr = GetComponent<Transform>();
        playerTr = GameObject.FindWithTag("Player").GetComponent<Transform>();
        agent = GetComponent<NavMeshAgent>();
        StartCoroutine(CheckMonsterState());
    }

    IEnumerator CheckMonsterState()
    {
        while (!isDie)
        {
            yield return new WaitForSeconds(0.3f);
            float distance = Vector3.Distance(playerTr.position, monsterTr.position);

            if(distance <= attckDist )
            {
                state = State.Attack;
                animator.SetInteger("state", (int)state);
                agent.SetDestination(transform.position);
            }
            else if (distance <= tranceDist)
            {
                state = State.Trace;
                animator.SetInteger("state", (int)state);
                LookAtPlayer();
                agent.destination = playerTr.position;
            }
            else
            {
                state=State.Idle;
                animator.SetInteger("state", (int)state);
            }
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("BULLET"))
        {
            isDie = true;
            state = State.Die;
            animator.SetInteger("state", (int)state);

            // NavMeshAgent 비활성화
            agent.enabled = false;

            // 코루틴 정지
            StopAllCoroutines();

          
        }
    }


    private void LookAtPlayer()
    {
        Vector3 direction = (playerTr.position - transform.position).normalized; // 플레이어 방향 계산
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z)); // 회전값
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f); //회전
    }

    private void OnDrawGizmos()
    {
        if(state == State.Trace)
        {
            Gizmos.color = Color.blue;
            Gizmos.DrawWireSphere(transform.position, tranceDist);
        }

        if(state == State.Attack)
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(transform.position, attckDist);
        }
    }
}

반응형

+ Recent posts