Unity 动态Navigation参数动态设置

Unity 动态Navigation方法,见上篇博客:https://blog.csdn.net/LM514104/article/details/115479030

自定义烘培参数:(在Bake()和UpdateNavMesh里面修改如下,(为做区分)异步自定义参数,同步用了默认参数)

 1、先定义外部可修改的参数:

  //用世界单位表示的代理的半径
    public float agentRadius = 0.2f;
    // 代理的高度,以世界单位计算
    public float agentHeight = 0.5f;
    //可步行的最大倾斜角(角度)。
    public float agentSlope = 10f;
    //代理可以采取的最大垂直步长。
    public float agentClimb = 0.5f;
    //单个导航网格区域的近似最小面积。 
    public float minRegionArea = 10;
    private NavMeshBuildSettings m_Setting;

2、Bake里面创建结构体:

 public void Bake()
    {
        // Construct and add navmesh
        m_Setting = NavMesh.CreateSettings();
        m_NavMesh = new NavMeshData();
        m_Instance = NavMesh.AddNavMeshData(m_NavMesh);
        if (m_Tracked == null)
            m_Tracked = transform;
        UpdateNavMesh(false);
    }

3、UpDateNavMesh里面更新烘培参数:  

void UpdateNavMesh(bool asyncUpdate = false)
    {
        NavMeshSourceTag.Collect(ref m_Sources);
        //var defaultBuildSettings = NavMesh.GetSettingsByID(0);
        m_Setting.agentRadius = agentRadius;
        // 代理的高度,以世界单位计算
        m_Setting.agentHeight = agentHeight;
        //可步行的最大倾斜角(角度)。
        m_Setting.agentSlope = agentSlope;
        //代理可以采取的最大垂直步长。
        m_Setting.agentClimb = agentClimb;
        //单个导航网格区域的近似最小面积。 
        m_Setting.minRegionArea = minRegionArea;
        var bounds = QuantizedBounds();
        if (asyncUpdate)
            m_Operation = NavMeshBuilder.UpdateNavMeshDataAsync(m_NavMesh, m_Setting, m_Sources, bounds);
        else
            NavMeshBuilder.UpdateNavMeshData(m_NavMesh, m_Setting, m_Sources, bounds);
    }

4、调用NavMeshAgent移动方法的时候注意:要为NavMeshAgent组件的AgentType设置对应寻路Mesh的枚举,如下:

using UnityEngine;
using UnityEngine.AI;
public class NavMoveTest : MonoBehaviour
{// 挂载到移动的物体上
    public Transform target;//移动到目标物体的位置,我外部随便拖了个物体
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.G))
        {
            NavMeshAgent agent = transform.GetComponent<NavMeshAgent>();
            if (agent == null)
            {
                agent = gameObject.AddComponent<NavMeshAgent>();
            }
            // GetSettingsByIndex () 根据创建的下表,索引到agentTypeID然后赋值
            agent.agentTypeID = NavMesh.GetSettingsByIndex(1).agentTypeID;
            agent.SetDestination(target.position);
        }
    }
}

 5、对应位置如下:

猜你喜欢

转载自blog.csdn.net/LM514104/article/details/115489066
今日推荐