实现寻路方法
-
确定寻路者
点击寻路者,点击菜单栏的Component->Navigation->Nav Mesh Agent -
烘焙寻路路面
- 将不动的物体设置为static
- 菜单栏windows->->AI->Navigation
- 点击Bake
- 给需要寻路的物体添加脚本脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
/// <summary>
/// 寻路
/// </summary>
public class NavMeshTest : MonoBehaviour
{
private NavMeshAgent agent;
public GameObject targetObject;
private void Start()
{
agent = this.GetComponent<NavMeshAgent>();
}
private void Update()
{
if(agent != null)
{
agent.SetDestination(targetObject.transform.position);
}
}
}
搭桥
- 菜单栏 Component->Navigation->Off Mesh Link
Navigation 属性面板说明
|Navigation Bake|说明|
|-------|-------|-------|
|AgentRadius|烘焙路径可行区域和非可行区域的间隔|
|AgentHeight|烘焙路径时当高度小于这个值的地方,就是不可行区域|
|Max Slope|最大可行区域的坡度|
|Step Height|最大台阶高度|
|Drop Height|下落高度|
|Jump Distance|最大跳跃距离|
Nav Mesh Agent组件
Agent Size | 尺寸控制 | |
---|---|---|
Radius | 物体碰撞的半径 | |
Height | 物体碰撞的高度 | |
Base Offset | 偏移度 | |
Steering | 行动控制 | |
Speed | 物体进行的最大速度 | |
Angular Speed | 行进过程中转向是的角速度 | |
Acceleration | 物体的行进加速度 | |
Stopping Distance | 距离目标点小于多远距离后便停止行进 | |
Obstacle Avoidance | 躲避障碍参数 | |
Quality | 质量 | |
Priority | 优先级 | |
Path Finding | 路径寻找 | |
Auto Traverse Off Mesh Link | 是否采用默认方式搭桥连接路径 | |
Auto Repath | 在行进过程中,因某些原因中断的情况下,是否重新开始寻路 | |
Area Mask | 区域覆盖,当前寻路组件没有覆盖的区域,即使有时可行区域,对当前这个组件来说也是不可行区域 |
- 区域遮罩
寻路者可以通过区域遮罩,选择不同路面,进行寻路效果
Nav Mesh Obstacle 寻路的动态碰撞
敌人在寻路的时候,会碰到附加了Nav Mesh Obstacle的物体,就会绕开这个物体
点击地面,让物体有寻路效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
/// <summary>
/// 射线
/// </summary>
public class Player : MonoBehaviour
{
private Ray ray;
private RaycastHit hit; // 射线触碰到的物体信息
private NavMeshAgent agent;
private void Start()
{
agent = this.GetComponent<NavMeshAgent>();
}
private void Update()
{
// 起始位置:主摄像机
// 方向:鼠标位置
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, 100) && Input.GetMouseButton(1))
{
agent.SetDestination(hit.point);
}
}
}
练习
- 如何制作一个小地图?
- 点击小地图的红绿蓝,人物就会移动到对应的位置
评论区