private IEnumerator UpdatePath() {
// 살아 있는 동안 무한 루프
while (!dead)
{
if(hasTarget)
{
//target exist : path update and keep moving
navMeshAgent.isStopped = false;
navMeshAgent.SetDestination(
targetEntity.transform.position);
}
else
{
//missing target : stop moving
navMeshAgent.isStopped = true;
//
Collider[] colliders =
Physics.OverlapSphere(transform.position, 20f, whatIsTarget);
//findout LivingEntity
for(int i = 0; i<colliders.Length; i++)
{
//pull out LivingEntity
LivingEntity livingEntity = colliders[i].GetComponent<LivingEntity>();
if(livingEntity != null && !livingEntity.dead)
{
//set LivingEntity to target
targetEntity = livingEntity;
break;
}
}
}
// 0.25초 주기로 처리 반복
yield return new WaitForSeconds(0.25f);
}
}
updatePath 메서드의 구현
좀비의 경로를 실시간으로 업데이트 하는 메서드의 구현입니다.
NavMeshAgent 의 사용
NavMeshAgent 컴포넌트를 추가하고 스크립트로 값을 조절하여 대상을 움직이게 하거나, 멈출 수 있습니다.
private NavMeshAgent navMeshAgent;
navMeshAgent.speed = zombieData.speed;
navMeshAgent.isStopped = false;
navMeshAgent.SetDestination(
targetEntity.transform.position);
스크립트 상에서 사용된 NavMeshAgent 내용들입니다.
speed = float 값으로 속도를 제어 할 수 있습니다.
isStopped = bool 값으로 이동할지 멈출지 제어할 수 있습니다.
SetDestination(Vector3) , 공간 좌표를 매개변수로 다루며 해당 좌표를 향해 이동하게 됩니다.
Physics.OverlapSphere
[ExcludeFromDocs]
public static Collider[] OverlapSphere(Vector3 position, float radius, int layerMask)
{
return OverlapSphere(position, radius, layerMask, QueryTriggerInteraction.UseGlobal);
}
layerMask는 32비트 int 형으로
32개까지만 만들 수 있는 비트형태로 오브젝트를 상징하여 구분할 수 있는 기능입니다.
00000000 00000000 00000000 00000000 <<< 이런식으로 32비트(4Bytes)를 표현할 수 있죠
whitIsTarget은
public LayerMask whatIsTarget;
이렇게 선언만 되었고 코드내에서 초기화 되지는 않았습니다.
Unity 인스펙터 창에서 직접 초기화 해 주어야 하겠습니다.
Physics.OverlapSphere(transform.position, 20f, whatIsTarget);
이렇게 사용하게 된다면 transform.position 좌표 상에서 반경20f 크기만큼을 검색하고, 그 중에서 whatIsTarget 레이어에 해당하는 콜라이더들만 반환하게 되는 것입니다.
이렇게 콜라이더들을 모아서 그중에 LivingEntity 가 있는지 검사하고 있다면 targetEntity의 값을 수정합니다.
targetEntity는 전역 변수로 이 오브젝트를 활용해서 타겟을 추적하게 됩니다.