Unity3d 根據鼠標點擊位置自動尋路

本博客只爲個人記錄筆記。
使用NavMeshAgent 組件,根據鼠標左鍵點擊位置進行自動尋路。
知道了需要到達的座標點(target)之後,直接使用下面代碼即可。

navMeshAgent.destination = target;

獲取鼠標點擊點在三維座標中的位置。
從攝像機出發,發出一條過鼠標點的射線。

Camera.main.ScreenPointToRay(Input.mousePosition);

使用 Physics.Raycast,獲取該設想與地面的交點,直接得到交點的座標point。

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

public class FindPath : MonoBehaviour
{
    private NavMeshAgent navMeshAgent;
    void Start()
    {
        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if(!Physics.Raycast(ray, out hit))
            {
                return;
            }
            Vector3 target = hit.point;
            navMeshAgent.destination = target;
            if(navMeshAgent.pathStatus == NavMeshPathStatus.PathInvalid)
            {
                return;
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章