首先将场景搭建好
添加一个玩家角色,想让玩家有自动寻路的功能需要在玩家的组件中添加一个Nav Mesh Agent组件。在场景中添加一个空物体作为目标点的位置。 然后给玩家添加脚本,内容如下
public class Actor : MonoBehaviour { public Transform goal;//目标位置 private NavMeshAgent agent; private void Start() { agent = GetComponent<NavMeshAgent>(); agent.destination = goal.position;//寻路目标点为设定好的目标点的位置 } }然后将目标点拖拽到脚本中的开放变量中,然后添加Navigation然后烘焙地图。运行即可得玩家自动移动到目标点的位置。
在上面的基础上在脚本中添加如下的内容
{ public Transform goal;//目标位置 private NavMeshAgent agent; private void Start() { agent = GetComponent<NavMeshAgent>(); agent.destination = goal.position;//寻路目标点为设定好的目标点的位置 } private void Update() { if (Input.GetMouseButtonDown(0))//点下鼠标左键 { RaycastHit hit;//利用射线查询函数来获取鼠标点选的三维位置 if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) { agent.destination = hit.point; } } }使用Off Mesh Link组件实现不可通过区域的链接 并把开始点和结束点的位置拖拽到相应的位置。
在场景中添加一个墙,会发现玩家会穿墙而过,这时候需要给墙添加一个Nav Mesh Obstacle组件。
其中Carve选项意思是如果勾选了之后烘焙出的区域就相当于一个静态物体,不勾选的话也有障碍的功能,但是不在烘焙的障碍区域中。