unity UGUI利用navmesh绘制小地图

游戏里面寻路如果不用a*很多情况用到navmesh

navmesh烘焙出来的导航网格都是可走的地方,这样来可以用来做小地图,我游戏项目是这样,不过还要看项目类型

实现思路

  • 获取导航图所有的顶点
  • 然后把所有点扔给一个可以画图形的控件

描绘顶点的控件

using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("UI/UIPopulateMesh")]
public partial class UIPopulateMesh : MaskableGraphic
{
    [SerializeField]
    Texture m_Texture;
    public System.Func<Texture> GetTexture;
    public System.Action<VertexHelper> PopulateMesh;
    public override Texture mainTexture
    {
        get
        {
            if (GetTexture != null)
            {
                return GetTexture.Invoke();
            }
            else if (m_Texture == null && material != null && material.mainTexture != null)
            {
                return material.mainTexture;
            }
            else
            {
                return m_Texture == null ? s_WhiteTexture : m_Texture;
            }
        }
    }

    public Texture texture
    {
        get
        {
            return m_Texture;
        }
        set
        {
            if (m_Texture == value)
                return;

            m_Texture = value;
            SetVerticesDirty();
            SetMaterialDirty();
        }
    }

    public void RefreshMap()
    {
        SetVerticesDirty();
        //SetMaterialDirty();
    }


    protected override void OnPopulateMesh(VertexHelper vh)
    {
        if (PopulateMesh != null)
        {
            PopulateMesh.Invoke(vh);
        }
    }
}

测试脚本

ugui 上面创建一个空节点挂UIPopulateMesh和testNavMap,前提是你的场景地图nav已经烘焙过

这个脚本获取所有navmesh所有顶点

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

public class testNavMap : MonoBehaviour
{
    private UIPopulateMesh mesh;

    private void Awake()
    {
        mesh.PopulateMesh += (PopulateMesh);
    }

    void PopulateMesh(VertexHelper vh)
    {
        var tr = UnityEngine.AI.NavMesh.CalculateTriangulation();
        vh.Clear();
        var vv = System.Array.ConvertAll<Vector3, Vector2>(tr.vertices, v3 =>
        {
            return new Vector2((v3.x), (v3.z));
        });
        vh.AddUIVertexStream(new List<UIVertex>(SetVbo(vv, new Vector2(0, 0), Color.grey)), new List<int>(tr.indices));
    }
    protected UIVertex[] SetVbo(Vector2[] vertices, Vector2 uv, Color32 color)
    {
        UIVertex[] vbo = new UIVertex[vertices.Length];
        List<Vector2> list = new List<Vector2>();
        for (int i = 0; i < vertices.Length; i++)
        {
            var v = vertices[i];
            var vert = UIVertex.simpleVert;
            vert.color = color;
            vert.position = v;
            vert.uv0 = uv;
            vbo[i] = vert;
        }
        return vbo;
    }
}

猜你喜欢

转载自blog.csdn.net/SnoopyNa2Co3/article/details/81544071