首先是地图烘焙介绍:
在窗口(Window)-AI-导航(Navagation)处打开导航窗口
在上述可以调整烘培的一些设置,代理半径与代理高度一般设为与玩家控制角色相同的半径与高度,最大坡度可按照实际情况设置。在进行烘培前,将场景中的一些地面物品设为Navigation Static
这样再点击Bake进行烘焙,可以看到场景中的蓝色部分为可到达的位置
之后为角色添加组件Nav Mesh Agent,并设置相关参数。
其中的半径与高度就是上面所说要与这里的半径高度对应。
接着添加代码,这里命名为ClickToMove,代码如下:这里还需要将之前设为Navigation Static的物体的标签设为Ground,这样添加下面代码后,就能实现点击烘培过的地面进行控制移动了。
using UnityEngine;
using UnityEngine.AI;
public class ClickToMove : MonoBehaviour
{
RaycastHit hit;
private NavMeshAgent agent;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
MouseController();
}
private void MouseController()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//检测射线
if(Physics.Raycast(ray, out hit))//hit获取射线检测到的物体
{
if (Input.GetMouseButtonDown(0))//鼠标左键按下
{
if (hit.collider.gameObject.CompareTag("Ground"))
{
agent.SetDestination(hit.point);//将点击位置设为移动目的地
}
}
}
}
}