本博客只爲個人記錄筆記。
使用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;
}
}
}
}