本文简述了Unity中绘制正五边形网格的基本方法:计算顶点信息、设置三角形覆盖信息、创建配置mesh
绘制方法
- 基本思路:计算出五边形顶点坐标信息作为数组,设置三角形包围方式,再创建新的mesh配置vertices、triangle参数,最终赋值到当前mesh上
- 项目实现:
- 创建DrawPentagon.cs,挂在于带有mesh的物体上(本例为Quad
- 编写代码如下:
- 查看所创建的mesh信息
public class DrawPentagon : MonoBehaviour { private Vector3[] newVertices; //五边形顶点数组 private int[] newTriangles; //五边形网格内的三角形网格信息 void Start() { //1. 创建五边形顶点坐标数组:顶点编号0~4 newVertices = new Vector3[5] { Vector3.zero, new Vector3(Mathf.Cos(Mathf.Deg2Rad * 36), 0, Mathf.Sin(Mathf.Deg2Rad * 36)), new Vector3(2 * Mathf.Cos(Mathf.Deg2Rad * 36), 0, 0), new Vector3(Mathf.Cos(Mathf.Deg2Rad * 72) + 1, 0, -Mathf.Sin(Mathf.Deg2Rad * 72)), new Vector3(Mathf.Cos(Mathf.Deg2Rad * 72), 0, -Mathf.Sin(Mathf.Deg2Rad * 72)) /* newVertices[0] = (0.0, 0.0, 0.0) newVertices[1] = (0.8, 0.0, 0.6) newVertices[2] = (1.6, 0.0, 0.0) newVertices[3] = (1.3, 0.0, -1.0) newVertices[4] = (0.3, 0.0, -1.0) */ }; //2. 设根据已有的顶点编号设置三角形包围顺序,例如0,1,2顶点围成一个三角形;0,2,3顶点围成另一三角形 newTriangles = new int[9] { 0, 1, 2, 0, 2, 3, 0, 3, 4 }; //错误情况:三角形数量不足 //newTriangles = new int[6] { 0, 1, 2, 0, 2, 3 }; //错误情况:三角形覆盖面不全 //newTriangles = new int[9] { 0, 1, 2, 1, 2, 3, 0, 3, 4 }; //3. 创建mesh信息:顶点数据、三角形 Mesh mesh = new Mesh { name = "Pentagon", vertices = newVertices, triangles = newTriangles }; GetComponent<MeshFilter>().mesh = mesh; } }
示意图及错误示例: