场景中有 Capsule,Cube,Plan
给Plane添加组件NavMesh Surface
给Capsule添加组件NavMesh Agent
给Cube添加组件NavMesh Obstacle
在Plane的Inspctor中点击Bake
程序代码如下:
public class BasickPatro : MonoBehaviour
{
public Transform[] waypoints;
NavMeshAgent agent;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
Debug.Log("the agent is: "+agent);
agent.destination = waypoints[0].position;
}
}
将代码挂载给Capsule, 新建一个Empty object,命名为pos1,将其挂载到waypoints里
完成1个目标点的寻路
在以上基础上完成多个点的来回巡逻:
将代码改写为:
using UnityEngine;
using UnityEngine.AI;
public class BasickPatro : MonoBehaviour
{
public Transform[] waypoints;
NavMeshAgent agent;
int index;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
//不断向当前位置点前进
InvokeRepeating("Tick", 0, 0.5f);
if (waypoints.Length > 0)
{
//5秒进入下个位置点
InvokeRepeating("Patrol", 0, 5f);
}
}
void Patrol()
{
//位置点是否到了最后一个,如果是重回第一个位置点,否则到下一个位置点
index = index == waypoints.Length - 1 ? 0 : index + 1;
}
void Tick()
{
agent.destination = waypoints[index].position;
}
}
在场景中添加多个pos点,全部将其挂载到waypoints里,完成多个固定点的巡逻