您好,登錄后才能下訂單哦!
這篇文章主要介紹Unity3D如何生成一段隧道網格,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
一、需求
最近有一個需求,生成段隧道的骨架網格。目前想到的方法就是,獲取隧道網格,通過一個算法分離內框和外框的點:
然后通過外框和內框上的點畫線,可以通過深度優先搜索得到內外兩個環的序列, 從而實現骨架網格
二、生成隧道算法
隧道由段圓弧和一條直線組成,所以算法如下:
1、取圓心為0,0,0,和圓上半徑的向量 \underset{OB}{\rightarrow} ,繞z軸,旋轉向量\underset{OB}{\rightarrow},取到圓上的點,外框上的點同理可得
2、平移內外框上的點,z軸加上偏離,得到隧道另一端的點
3、取相鄰外框上的點和平移后的四個點,生成兩個三角形。內框同理可得。
三、效果如下:
四、實現:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeshCreater : MonoBehaviour { Mesh mesh; public Material mat;//mesh材質 public GameObject game; // Start is called before the first frame update void Start() { mesh = new Mesh(); mesh.Clear(); SetVertivesUV(); SetTriangles(); mesh.vertices = vertices.ToArray(); mesh.triangles = triangles; GameObject obj_cell = new GameObject(); obj_cell.name = "cell"; mesh.RecalculateNormals();//重置法線 mesh.RecalculateBounds(); //重置范圍 obj_cell.AddComponent<MeshFilter>().mesh = mesh; obj_cell.AddComponent<MeshRenderer>(); obj_cell.GetComponent<MeshRenderer>().material = mat; MeshCaluate mesh_caluate = new MeshCaluate(); mesh_caluate.CalculateMesh(mesh); } // Update is called once per frame void Update() { } public List<Vector3> vertices = new List<Vector3>(); private float angle = 10; private float max_angle = 120; // 設置頂點信息 void SetVertivesUV() { Vector3 dir1 = new Vector3(Mathf.Sqrt(3f), -1, 0); Vector3 dir2 = dir1 * 0.8f; List<Vector3> points1 = new List<Vector3>(); List<Vector3> points2 = new List<Vector3>(); int count = (int)((360 - max_angle) / angle); for (int i = 0; i < count; i++) { Quaternion q= Quaternion.AngleAxis(i * angle, Vector3.forward); Vector3 point1 = q* dir1; Vector3 point2 = q* dir2; points1.Add(point1); points2.Add(point2); } points1.Add(points1[0]); points2.Add(points2[0]); for (int i = 0; i < points1.Count; i++) { var v1 = points1[i]; var v2 = points2[i]; var v3 = points1[i]; v3.z = 10; var v4 = points2[i]; v4.z = 10; vertices.Add(v1); vertices.Add(v3); vertices.Add(v2); vertices.Add(v4); } } private int[] triangles;//索引 // 設置索引 void SetTriangles() { triangles = new int[vertices.Count * 3]; int c = 0; for (int i = 0; i < triangles.Length -12 ; i += 12) { var v1 = c; var v2 = c + 1; var v3 = c + 4; var v4 = c + 5; var v5 = c + 2; var v6 = c + 3; var v7 = c + 6; var v8 = c + 7; triangles[i] = v4; triangles[i + 1] = v2; triangles[i + 2] = v1; triangles[i + 3] = v3; triangles[i + 4] = v4; triangles[i + 5] = v1; triangles[i + 6] = v5; triangles[i + 7] = v6; triangles[i + 8] = v8; triangles[i + 9] = v5; triangles[i + 10] = v8; triangles[i + 11] = v7; c += 4; } } }
五、缺陷
UV未計算,所以使用貼圖時有問題
以上是Unity3D如何生成一段隧道網格的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。