Unity3D生成一段隧道网格的方法
本文实例为大家分享了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未计算,所以使用贴图时有问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
C#中IEnumerable、ICollection、IList、List之间的区别
IEnumerable、ICollection、IList、List之间的区别,本文分别分析了它的实现源码,从而总结出了它们之间的关系和不同之处。对C# IEnumerable、ICollection、IList、List相关知识,感兴趣的朋友一起看看吧2021-07-07
最新评论