Unity C# 네비게이션 클릭(터치) 이동

Intro

유니티 네비게이션을 이용한 클릭 이동

네비게이션 영역 생성

1

2

적용할 오브젝트를 선택하고 네비게이션 영역을 Bake하여 이동가능한 공간을 생성한다.

네비메쉬 에이전트 추가

3

네비게이션을 사용할 캐릭터에 네비메쉬 에이 전트를 추가했다.

캐릭터 이동 스크립트 작성

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

public class Player : MonoBehaviour
{
    NavMeshAgent agent;
    public Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if(Application.platform==RuntimePlatform.Android) // 안드로이드 터치 이동
        {
            if(Input.touchCount>0&& Input.GetTouch(0).phase==TouchPhase.Moved)
            {
                Vector3 pos = Input.GetTouch(0).position;

                Ray ray = Camera.main.ScreenPointToRay(pos);
                RaycastHit hit;

                if(Physics.Raycast(ray, out hit))
                {
                    animator.SetBool("IsRun", true);
                    agent.SetDestination(hit.point);
                    agent.isStopped = false;
                }
               
            }

            if (agent.remainingDistance <= 0.2f && agent.velocity.magnitude >= 0.2f)
            {
                Debug.Log("idle");
                animator.SetBool("IsRun", false);
            }
        }
        else // 마우스 클릭 이동
        {
            if (Input.GetMouseButtonDown(0))
            {

                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit,100))
                {
                    animator.SetBool("IsRun", true);
                    agent.SetDestination(hit.point);
                    agent.isStopped = false;

                }

                
            }

            if (agent.remainingDistance <= 0.2f && agent.velocity.magnitude >= 0.2f)
            {
                animator.SetBool("IsRun", false);
            }
        }
    }
}

이동을 원하는 지점 클릭(터치)시 메인카메라에서 클릭한 지점에 Raycast 하여 충돌된 지점으로 에이전트에 이동명령을 내리도록 구성했다.

실행결과

gif

참고자료

https://youtu.be/Ab768txT9SM?list=PLqnN6EfbDpKYdktgLMPQKYSK4CFYc6iK4

태그: ,

카테고리:

업데이트:

댓글남기기