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

반응형
'KDT > 유니티 심화' 카테고리의 다른 글
[SpaceShooter] Player와 Monster 사망 시 동작(애니메이션) 구현 (0) | 2023.08.24 |
---|---|
[SpaceShooter] Monster 공격과 피격 구현 (0) | 2023.08.24 |
[SpaceShooter] 가장 가까운 적에게 총 발사하기 (0) | 2023.08.22 |
[SpaceShooter] 가까운 오브젝트 장착하기 (OverlapSphereNonAlloc) (0) | 2023.08.21 |
[SpaceShooter] 총알이 벽에 닿았을 때 튕기게 만들기 (0) | 2023.08.21 |