unity中动态生成网格
Posted 露夕逝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity中动态生成网格相关的知识,希望对你有一定的参考价值。
以下是绘制正方形面片的一个例子,方便之后查阅:
效果如图所示:
红轴为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 /// <summary> 16 /// 创建mesh 17 /// </summary> 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<MeshFilter>().mesh = mesh; 34 obj_cell.AddComponent<MeshRenderer>(); 35 obj_cell.GetComponent<MeshRenderer>().material = mat; 36 } 37 38 /// <summary> 39 /// 设置顶点信息 40 /// </summary> 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 /// <summary> 57 /// 设置索引 58 /// </summary> 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
以上是关于unity中动态生成网格的主要内容,如果未能解决你的问题,请参考以下文章
Unity 动态网格地图的生成:基于Perlin Noise创建地形
游戏开发进阶Unity网格探险之旅(Mesh | 动态合批 | 骨骼动画 | 蒙皮 )