개발/Unity

유니티 - 네비메쉬 에이전트로 장애물 피하면서 이동하기

피로물든딸기 2022. 8. 25. 20:29
반응형

Unity 전체 링크

 

유니티가 제공하는 AI 기능을 이용하여 물체가 장애물을 피하면서 이동해보자.

 

아래와 같이 평면에 장애물(Wall)을 배치하자.

하얀색 큐브Player, 검은색 작은 큐브도착점이다.

 

이제 하얀색 큐브 = NavMeshAgent 컴포넌트를 추가하고,

평면과 장애물을 Bake해서 움직일 수 있는 경로를 만들자.

[Window] → [AI] → [Navigation]을 클릭하자.

 

평면은 기본적으로 움직이는 공간이므로, 평면을 선택한 후,

[Navigation] → [Object] → Navigation Static 체크, Navigation Area = Walkable로 설정한다.

 

장애물은 이동할 수 없는 공간이므로 모두 선택한 후, 아래와 같이 Not Walkable로 설정한다.

 

이제 Bake에서 굽는다. 

Agent Radius가 0.5인 경우 아래와 같이 이동 경로가 설정된다.

 

Radius를 줄이면 조금 더 넉넉하게 움직일 수 있다. 여기서는 0.3으로 설정하였다.

 

이제 Player 큐브에 NavMeshAgent 컴포넌트를 추가하고 PathFinder.cs를 추가한다.

target은 검은색 큐브가 된다.

 

NavMeshAgent에는 설정할 값이 여러 개 있는데,

여기서는 SpeedAcceleration을 각각 5, 16으로 수정하였다.

 

PathFinder.cs는 아래와 같다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class PathFinder : MonoBehaviour
{
    public GameObject target;
    NavMeshAgent agent;

    void Start()
    {
        agent = this.GetComponent<NavMeshAgent>();
        agent.SetDestination(target.transform.position);
    }
}

 

게임을 실행하면 아래와 같이 Target의 position으로 이동한다.

NavMeshAgent가 적절히 방향까지 전환하면서 도착점까지 이동한다.


선택한 위치로 이동하기

 

마우스로 클릭하면 Target을 옮겨 변경된 위치로 이동하도록 해보자.

 

PathFinder.cs를 아래와 같이 수정한다.

    void Start()
    {
        agent = this.GetComponent<NavMeshAgent>();
    }
    
    public void goTarget()
    {
        agent.SetDestination(target.transform.position);
    }

 

그리고 TargetChanger.cs를 Target 큐브에 추가한다.

Raycast로 클릭한 평면의 좌표(hit.point)를 찾은 후, Player의 goTarget()을 실행한다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetChanger : MonoBehaviour
{
    RaycastHit hit;
    public GameObject player;

    void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 100.0f, Color.red);

            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                this.transform.position = hit.point;
                player.GetComponent<PathFinder>().goTarget();
            }
        }
    }
}

 

그리고 player에 하얀색 큐브를 추가한다.

 

이제 평면을 클릭하면 도착점이 바뀌고, 클릭한 위치로 이동하게 된다.

 

이제 NavMeshAgent가 움직이는 경로를 라인 렌더러로 그리면서 움직여보자.

 

Unity Plus:

 

Easy 2D, 3D, VR, & AR software for cross-platform development of games and mobile apps. - Unity Store

Have a 2D, 3D, VR, or AR project that needs cross-platform functionality? We can help. Take a look at the easy-to-use Unity Plus real-time dev platform!

store.unity.com

 

Unity Pro:

 

Unity Pro

The complete solutions for professionals to create and operate.

unity.com

 

Unity 프리미엄 학습:

 

Unity Learn

Advance your Unity skills with live sessions and over 750 hours of on-demand learning content designed for creators at every skill level.

unity.com

반응형