[Unity #필드액션게임프로젝트] <Temptation of food> 목표물 따라가기 (Navigation, AI 기능 활용법)
목표물(target)을 찾아가는 추적자 만들기
1. 먼저, 3D Object > Cube를 활용하여 Floor를 생성한다.
2. Window > Ai > Navigation을 누르면 Inspecter창 옆에 Navigation창이 생긴다.
(Window는 화면 좌측 최상단에 있음.)
3. Floor > Navigation > Object > Navigation Static
Navigation Static 박스를 체크해준다.
4. Floor > Navigation > Bake > Bake
Bake에 들어가서 Bake 버튼을 누른다.
Bake 버튼을 누르게 되면, 아래 화면과 같이 Floor 위에 하늘색이 생긴다.
이 하늘색 영역은 추적자가 목표물을 쫓아갈 때, 길 탐색이 가능한 영역을 뜻한다.
5. 3D Object > Sphere
추적자의 목표물이 될 target을 생성한다.
6. 3D Object > Cylinder > Inspector > Add Component > Nav Mesh Agent
추적자(Cylinder)를 생성하고, Inspector창에 Nav Mesh Agent를 추가해준다.
7. Cylinder > Inspector > Add Component > GoTo
GoTo > Goal > target
C# 스크립트를 작성하고, Cylinder의 Inspector창에 추가해준다.
그리고 Goal에 target을 넣어, 목표지점 설정을 완료한다.
주의) 꼭 추적자의 Inspector 창에 스크립트를 추가해준다.
using UnityEngine;
using System.Collections;
using UnityEngine.AI;
public class GoTo : MonoBehaviour
{
public Transform goal;
void Start()
{
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.destination = goal.position;
}
}
여기까지 하고 플레이 버튼을 누르면 추적자가 target을 찾아가는 것을 볼 수 있다.
+ 장애물을 피해서 목표물(target)까지 가기
8. 3D Object > Cube
방해물(Obstacle)을 추가해준다.
9. Obstacle > Inspector > Add Component > Nav Mesh Obstacle
Obstacle의 Inspector창에 Nav Mesh Obstacle을 추가해준다.
주의) Nav Mesh Obstacle은 Collider를 기반으로 모양을 만들기 때문에 Collider가 없으면 작동하지 않는다.
방해물에 Collider가 있는지 꼭 확인하기!
10. Obstacle > Navigation > Object > Navigation Static
Obstacle > Navigation > Object > Navigation Area > Not Walkable
Navigation의 Object에 들어가서 Navigation Static 박스를 체크해준다.
방해물은 뚫고 지나가면 안 되기 때문에 Navigation Area의 Walkable 설정을 Not Walkable로 바꿔준다.
11. Obstacle > Navigation > Bake > Bake
Bake 버튼을 눌러준다.
주의) 만약, 1차 Bake 후에 방해물의 크기를 바꾸었다면 다시 Bake 해주어야 한다.
여기까지 하고 플레이 버튼을 누르면 방해물(Obstacle)을 피해 target까지 갈 수 있다.
+ 플레이어의 위치가 바뀌어도 계속 따라가게 하기
12. GoTo 스크립트를 수정한다.
using UnityEngine;
using System.Collections;
using UnityEngine.AI;
public class GoTo : MonoBehaviour
{
public Transform goal;
NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
agent.destination = goal.position;
}
}