Unity3d NavMeshAgent自动寻路组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leonardo_Davinci/article/details/78288975

我们常见的有三种寻路方式

1.路点寻路

2.单元格寻路

3.网格寻路

简单介绍一下

1.路点寻路 如下图,物体从 point位置出发依次经过(point1 、point2、point3、point4、point5)进行移动

代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WayPointPath : MonoBehaviour {
    //所有路点的父物体
    private Transform point_parent;
    private int k=0;
	// Use this for initialization
	void Start () {
        //获取路点的父物体
        point_parent = GameObject.FindWithTag("Way").transform;

	}
	
	// Update is called once per frame
	void Update () {
        PointToPoint();
	}
    //物体按照路点移动
    void PointToPoint()
    {
        //判断物体到下一个路点的距离
        if (Vector3.Distance(transform.position, point_parent.GetChild(k).position) > 1f)
        {
            //用Vector3.Lerp移动
            transform.position = Vector3.Lerp(transform.position, point_parent.GetChild(k).position, 0.1f);
        }
        else
        {
            k=(k+1)%point_parent.childCount;
        }
    }
}

2.单元格寻路,

A*算法插件

与贪婪算法不一样,贪婪算法适合动态规划,寻找局部最优解,不保证最优解。A*是静态网格中求解最短路最有效的方法。也是耗时的算法,不宜寻路频繁的场合。一般来说适合需求精确的场合。

与启发式的搜索一样,能够根据改变网格密度、网格耗散来进行调整精确度。

使用较好的地方:
a.策略游戏的策略搜索
b.方块格子游戏中的格子寻路

3.网格寻路(NavMeshAgent)

实现寻路步骤:

  1. 将场景中不动的物体勾选static,

到window中调出 视窗,点击Bake烘焙,形成寻路(蓝色)网格。

  1. 需要自动寻路的物体,选中要寻路的物体 在Component添加NavMeshAgent自动寻路组件。

        

  1. 添加脚本

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//寻路要引入的命名空间
using UnityEngine.AI;

public class NewBehaviourScript : MonoBehaviour {
    //通过寻路要去找到的  目标物体
    public Transform target;
    //寻路组件
    private NavMeshAgent agent;
	// Use this for initialization
	void Start () {
        //获取寻路物体上的NavMeshAgent组件
        agent = GetComponent<NavMeshAgent>();
        //通过SetDestination方法(网格路径计算)实现自动寻路
        agent.SetDestination(target.position);
	}
}

  • NavMeshAgent属性

Radius 寻路的碰撞半径

Height寻路的碰撞高度

BaseOffset 寻路碰撞的位置

Speed 寻路物体的速度

Acceleration 转弯时的加速度

AngularSpeed 转弯时物体的角速度

StoppingDistance 停止的距离

AvoidancePriority 躲避系数

  • 寻路路径烘焙属性

Radius 是指寻路区域与障碍物之间半径

Height 是指寻路区域与地面之间的高度

MaxSlope 是指寻路区域烘焙的最大坡度

StepHeight 是指台阶高度

  • 寻路系统区域遮罩:
  1.   分别添加自定义区域,如Red、Blue区域.
  2. 选择场景中的静态路面      指定到相应寻路区域
  3. Bake寻路路面。
  4. 找到需要寻路的物体,设置可在寻路路面行走的区域。


(PS:Cost:寻路区域消耗度,数值越大,从此寻路区域消耗越大。

寻路物体在区域消耗数值一样的情况下,会选择最优(最近)路面寻路,但如果寻路区域的消耗数值不同,会根据消耗的数值,越小越最优进行寻路。)

  • 通过代码实现勾选不同的寻路区域:

GetComponent<NavMeshAgent>().areaMask =9;

寻路区域每一区域都是2的幂

 

9则为Walkable区域(1)+red区域(8) = 9

Everything所有区域-1   Nothing任何区域都不能寻路 0




猜你喜欢

转载自blog.csdn.net/leonardo_Davinci/article/details/78288975