TigerProject/Assets/Test/Monster/FlyEnemyMovement.cs

71 lines
1.7 KiB
C#

using UnityEngine;
using UnityEngine.AI;
public class FlyEnemyMovement : Entity
{
private GameObject playerObject;
private NavMeshAgent agent;
[SerializeField]
private float detectionRange = 5.0f; // 감지 범위 변수
[SerializeField]
private float EnemyTime;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
// NavMeshPlus 2D 설정
agent.updateRotation = false;
agent.updateUpAxis = false;
}
private void Start()
{
playerObject = GameObject.FindWithTag("Player");
}
void Update()
{
if (playerObject != null)
{
// 1. 현재 위치와 플레이어 위치 사이의 거리를 계산
float distance = Vector3.Distance(transform.position, playerObject.transform.position);
// 2. 거리가 감지 범위 확인
if (distance <= detectionRange)
{
SetAgentPosition(); // 추격 시작
}else
{
// 범위 밖이라면 이동을 멈춤
if (!agent.isStopped)
{
agent.ResetPath();
}
}
}
}
private void SetAgentPosition()
{
if (!agent.isActiveAndEnabled || !agent.isOnNavMesh)
{
return;
}
Vector3 targetPos = playerObject.transform.position;
agent.SetDestination(new Vector3(targetPos.x, targetPos.y));
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Die();
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, detectionRange);
}
}