实现寻路方法

  • 确定寻路者
    点击寻路者,点击菜单栏的Component->Navigation->Nav Mesh Agent

  • 烘焙寻路路面

  1. 将不动的物体设置为static
  2. 菜单栏windows->->AI->Navigation
  3. 点击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

image.png

|Navigation Bake|说明|
|-------|-------|-------|
|AgentRadius|烘焙路径可行区域和非可行区域的间隔|
|AgentHeight|烘焙路径时当高度小于这个值的地方,就是不可行区域|
|Max Slope|最大可行区域的坡度|
|Step Height|最大台阶高度|
|Drop Height|下落高度|
|Jump Distance|最大跳跃距离|

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的物体,就会绕开这个物体

点击地面,让物体有寻路效果

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);
        }
    }

}

练习

  • 如何制作一个小地图?
  • 点击小地图的红绿蓝,人物就会移动到对应的位置
    image.png