상세 컨텐츠

본문 제목

유니티 AI navigation 사용, 적 추적하기, 추적 범위 확인하기

유니티/기능

by MJ_119 2024. 9. 10. 14:05

본문

- 목표가 특정 거리 안에 있을때 적 추적하기, 따라가기

 - 이 코드는 범위 안에 캐릭터가 들어가자마자 범위를 벗어나도, 캐릭터가 범위 안으로 들어갔을때 위치까지 적 이동한다.

 - 마지막으로 감지된 위치가 범위에 들어온 위치이기 때문.

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

 

  • OnDrawGizmosSelected: 오브젝트가 선택되었을 때만 기즈모를 그린다. 불필요한 기즈모를 보지 않게 해 줌.
  • OnDrawGizmos: 항상 기즈모를 그린다. 선택 여부와 관계없이 항상 범위나 상태를 확인할 때 유용.

 

 

 

@ 한번 탐지되면 끝까지 따라가는 코드

 

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

 

 

관련글 더보기