- 목표가 특정 거리 안에 있을때 적 추적하기, 따라가기
- 이 코드는 범위 안에 캐릭터가 들어가자마자 범위를 벗어나도, 캐릭터가 범위 안으로 들어갔을때 위치까지 적 이동한다.
- 마지막으로 감지된 위치가 범위에 들어온 위치이기 때문.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyTrace : MonoBehaviour
{
[SerializeField] Transform target_Player;
[SerializeField] float chaseRange = 10f;
NavMeshAgent agent;
float distanceToTarget = Mathf.Infinity;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
// 타겟과 나 사이의 거리 구하기
distanceToTarget = Vector3.Distance(target_Player.position, transform.position);
if(distanceToTarget < chaseRange)
{
agent.SetDestination(target_Player.position);
}
}
}
- 추적 범위 확인하기
OnDrawGizmosSelected() 을 사용해서 플레이 하기 전에 본다.
using UnityEngine;
using UnityEngine.AI;
public class EnemyTrace : MonoBehaviour
{
[SerializeField] Transform target_Player;
[SerializeField] float chaseRange = 10f;
NavMeshAgent agent;
float distanceToTarget = Mathf.Infinity;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
// 타겟과 나 사이의 거리 구하기
distanceToTarget = Vector3.Distance(target_Player.position, transform.position);
if(distanceToTarget < chaseRange)
{
agent.SetDestination(target_Player.position);
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
}
@ 두개의 차이점 : Selected()는 플레이 하기전 오브젝트를 선택 했을때에만 화면에서 보임.
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, chaseRange);
}
@ 한번 탐지되면 끝까지 따라가는 코드
using UnityEngine;
using UnityEngine.AI;
public class EnemyTrace : MonoBehaviour
{
[SerializeField] Transform target_Player;
[SerializeField] float chaseRange = 10f;
NavMeshAgent agent;
float distanceToTarget = Mathf.Infinity;
bool isProvoked;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
// 타겟과 나 사이의 거리 구하기
distanceToTarget = Vector3.Distance(target_Player.position, transform.position);
if(isProvoked)
{
EngageTarget();
}
else if(distanceToTarget < chaseRange)
{
isProvoked = true;
//agent.SetDestination(target_Player.position);
}
}
private void EngageTarget()
{
// stoppingDistance(목표와 X거리 앞에서 멈춤)보다 멀리있으면 이동.
if(distanceToTarget >= agent.stoppingDistance)
{
//추적
ChaseTarget();
}
if (distanceToTarget <= agent.stoppingDistance)
{
// 공격
AttackTarget();
}
}
private void AttackTarget()
{
Debug.Log("Attack!!");
}
private void ChaseTarget()
{
agent.SetDestination(target_Player.position);
}
유니티 죽었을때 UI 띄우기 (0) | 2024.09.12 |
---|---|
유니티 레이캐스트로 총 맞은 곳에 이펙트(파티클) 생성하기 (0) | 2024.09.11 |
유니티 벽 미끄러지기 (0) | 2024.09.10 |
유니티 길찾기 알고리즘 (1) | 2024.09.10 |
유니티 그리드 적 소환하기 (1) | 2024.09.05 |