Web

스터디노트 03 - code: NavMesh

또롱또 2020. 9. 28. 18:57
728x90

NavMesh

 

탭 열기: window - ai - navigation

 

처음에는 Agents에서 내가 설정한 케릭터와 같게, radius height 등등을 설정

Object항목에서 Mesh Renderer로 매쉬들 중에 빌드를 할 오브젝트들을 선택. --> Navigation static 체크(네비게이션으로 사용), 이제 이동할곳은 walkable, 아닌곳은 아니게 설정 (터레인쪽도 같게 해주면됌)

 

최종적으로 Bake를 해주어야지 네비게이션 만들어짐

 

NavMesh Agent

 - Base Offset: 높이

 - Steering: NavMesh가 이동에 관련된거

 - Obstacle Avoidance: 물체 회피에 관련 

 

 

public class ControllerScript : MonoBehaviour
{
    #region Variables
    //get NavMesh
    private NavMeshAgent navMeshAgent;
    private Camera camera;

    //to get CharacterController from the unity
    private CharacterController characterController;

    //to calculate
    private Vector3 calcVelocity = Vector3.zero;

    //prevent double jump
    private bool isGround = false;
    [SerializeField]
    float groundCheckDistance = 0.3f;

    // to set layers
    [SerializeField]
    LayerMask groundLayerMask;
    #endregion

    // Start is called before the first frame update
    void Start()
    {
        //to get CharacterController from the unity
        characterController = GetComponent<CharacterController>();
        navMeshAgent = GetComponent<NavMeshAgent>();

        // will use character controller position
        navMeshAgent.updatePosition = false;
        navMeshAgent.updateRotation = true;

        camera = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {

        // 0 - left mouse click
        if (Input.GetMouseButtonDown(0))
        {
            // Make ray from screen to world
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);

            // Check hit
            RaycastHit raycastHit;
            if (Physics.Raycast(ray, out raycastHit, 100, groundLayerMask))
            {
                Debug.Log("We hit " + raycastHit.collider.name + " " + raycastHit.point);

                // Move our player to what we hit
                navMeshAgent.SetDestination(raycastHit.point);
            }
        }

        if (navMeshAgent.remainingDistance > navMeshAgent.stoppingDistance)
        {
            characterController.Move(navMeshAgent.velocity * Time.deltaTime);
        }
        else
        {
            characterController.Move(Vector3.zero);
        }
    }
    private void LateUpdate()
    {
        transform.position = navMeshAgent.nextPosition;
    }
} 
728x90