以下是绘制正方形面片的一个例子,方便之后查阅:
效果如图所示:
红轴为x方向,蓝轴为z方向。
代码如下:
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 public class SingleMesh:MonoBehaviour 5 { 6 public int size = 1;//边长 7 public int segment = 5;//分段数 8 public Material mat;//mesh材质 9 private Vector3[] vertices;//顶点10 private Vector2[] uv;//纹理坐标11 private int[] triangles;//索引12 13 14 [ContextMenu("Create Mesh")]15 ///16 /// 创建mesh17 /// 18 private void CreateMesh()19 {20 GameObject obj_cell = new GameObject();21 obj_cell.name = "cell";22 Mesh mesh = new Mesh();23 mesh.Clear();24 SetVertivesUV();//生成顶点和uv信息25 SetTriangles();//生成索引26 mesh.vertices = vertices;27 mesh.uv = uv;28 mesh.triangles = triangles;29 30 mesh.RecalculateNormals();//重置法线31 32 mesh.RecalculateBounds(); //重置范围33 obj_cell.AddComponent().mesh = mesh;34 obj_cell.AddComponent ();35 obj_cell.GetComponent ().material = mat;36 }37 38 /// 39 /// 设置顶点信息40 /// 41 private void SetVertivesUV()42 {43 vertices = new Vector3[(segment + 1) * (segment + 1)];44 uv = new Vector2[vertices.Length];45 int num = 0;46 float m = (float)size / (float)segment;47 for (int i = 0; i < segment + 1; i++)48 for (int j = 0; j < segment + 1; j++)49 {50 vertices[num] = new Vector3(j * m,0, i * m);51 uv[num] = new Vector2((float)j / segment, (float)i / segment);52 num++;53 }54 55 }56 ///57 /// 设置索引58 /// 59 private void SetTriangles()60 {61 triangles = new int[segment * segment * 6];62 int index = 0;//用来给三角形索引计数63 for (int i = 0; i < segment; i++)64 for (int j = 0; j < segment; j++)65 {66 int line = segment + 1;67 int self = j + (i * line);68 69 triangles[index] = self;70 triangles[index + 1] = self + line + 1;71 triangles[index + 2] = self + 1;72 triangles[index + 3] = self;73 triangles[index + 4] = self + line;74 triangles[index + 5] = self + line + 1;75 76 index += 6;77 }78 }79 }
其中triangles索引为链接各定点的顺序,一个小格的链接顺序如下:
准则:三角形有两面,正面可见,背面不可见。三角形的渲染顺序与三角形的正面法线呈左手螺旋定则。大部分按顺时针:012,213