Unity3D生成一段隧道网格的方法
程序员文章站
2022-07-03 08:29:04
本文实例为大家分享了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未计算,所以使用贴图时有问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 生成树【02】RSTP原理详解及配置实例