unity 把网格(mesh)绘制到UI上,可用于小地图
程序员文章站
2024-03-24 13:16:46
...
之前有个版本利用navmesh绘制小地图
这次使用场景的网格来绘制小地图
实现原理
- 获取mesh的顶点和三角面数据
- 然后通过VertexHelper来进行绘图
工程下载地址
链接:https://pan.baidu.com/s/1jH857JCjAqjsB3RkxaW9jA
提取码:x0kj
代码逻辑都比较简单,直接上图先
深紫色是场景网格,灰色是绘制在ui
控件代码之前用navmesh有提及过可以看看下面链接
https://blog.csdn.net/SnoopyNa2Co3/article/details/81544071
下面是测试代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TestMap : MonoBehaviour
{
/// <summary>
/// 绘制控件
/// </summary>
public UIPopulateMesh UIPopulateMeshmesh;
/// <summary>
/// 场景mesh
/// </summary>
public Mesh mesh;
private void Awake()
{
UIPopulateMeshmesh.PopulateMesh += (PopulateMesh);
}
void PopulateMesh(VertexHelper vh)
{
vh.Clear();
var vv = System.Array.ConvertAll<Vector3, Vector2>(mesh.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>(mesh.triangles));
}
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;
}
}
下一篇: Unity联网对战游戏小Demo