【Unity】Mesh网格编程(四)麦比乌斯环
生活随笔
收集整理的這篇文章主要介紹了
【Unity】Mesh网格编程(四)麦比乌斯环
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
事隔四個多月,第二篇網格編程原創,本次獻給大家的是麥比烏斯環。
其實這個早就想做了,還是輕松下來的時候思緒轉的快。
不廢話,先看效果:
博文首發:http://blog.csdn.net/duzixi
工程資源準備:
1. 本腳本要放在Editor文件夾下
2. 在資源中有一個空對象,作為頂點預設體,創建時要引入
3. 在Resources文件夾下有一個材質,叫"M"
源代碼:
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; /// <summary> /// 腳本功能:擴展Unity編輯器,在GameObject目錄下添加“麥比烏斯帶”目錄以向導方式生成麥比烏斯帶3D模型對象 /// 添加對象:無(在Editor文件夾中) /// 創建時間:2015年6月27日14:16:16 /// 創建人員:杜子兮 /// 版權聲明:2015 www.duzixi.com /// 技術要點: /// 1. 通過生成,父子化和旋轉空對象確認各個頂點位置 /// 2. 根據幾何頂點位置生成網格頂點位置 /// </summary> public class CreateMesh : ScriptableWizard {public int n = 50; // 切割數public float r = 5; // 半徑public float h = 0.2f; // 半高public GameObject point; // 頂點的預設體(選擇適當的圖標可顯示頂點號)[MenuItem("GameObject/麥比烏斯帶")]static void Create() {DisplayWizard<CreateMesh>("創建麥比烏斯帶", "創建");}void OnWizardCreate() {// Step 1: 確定頂點位置List<Vector3> vList = new List<Vector3>();GameObject obj = new GameObject(); // 實例化要生成的目標對象obj.name = "麥比烏斯帶";float angle = 2 * Mathf.PI / n; // 計算單位弧度for (int i = 0; i < n; i++){// 分別計算帶子上中下三個頂點位置并保存到數組中Vector3 center = new Vector3(Mathf.Cos(angle * i), 0, Mathf.Sin(angle * i));Vector3[] vs = new Vector3[3] { center, center + h * Vector3.down, center + h * Vector3.up };// 計算中心點的角度,使之朝向坐標原點Quaternion rot = Quaternion.Euler(new Vector3(0, -90 - 360 / n * i, 0));// 生成頂點對象GameObject p0 = Instantiate(point, vs[0], rot) as GameObject ;GameObject p1 = Instantiate(point, vs[1], Quaternion.identity) as GameObject;GameObject p2 = Instantiate(point, vs[2], Quaternion.identity) as GameObject;// 設置頂點名字(用于調試)p0.name = "c" + i;p1.name = 2 * i + "";p2.name = 2 * i + 1 + "";// 讓上下邊緣的點認中心點為父對象p0.transform.parent = obj.transform;p1.transform.parent = p0.transform;p2.transform.parent = p0.transform;// 通過旋轉中心點,改變上下邊緣頂點的位置p0.transform.Rotate(Vector3.right, 360 / n * i);// 將上下邊緣頂點添加到頂點列表中vList.Add(p1.transform.position);vList.Add(p2.transform.position);}// Step 2: 生成頂點數組Vector3[] Vs = new Vector3[6 * n];int index = 0;for (int i = 0; i < 2 * n - 2; i += 2){Vs[index++] = vList[i];Vs[index++] = vList[i + 1];Vs[index++] = vList[i + 2];Vs[index++] = vList[i + 2];Vs[index++] = vList[i + 1];Vs[index++] = vList[i + 3];}// 結合處頂點Vs[index++] = vList[2 * n - 2];Vs[index++] = vList[2 * n - 1];Vs[index++] = vList[0];Vs[index++] = vList[1];Vs[index++] = vList[0];Vs[index++] = vList[2 * n - 1];// Step 3: 締造三角形索引int[] Ts = new int[Vs.Length];for (int i = 0; i < Vs.Length; i++){Ts[i] = i;}// Step 4: 給目標對象添加網格組件obj.AddComponent<MeshFilter>();obj.AddComponent<MeshRenderer>();Mesh mesh = new Mesh();mesh.vertices = Vs;mesh.triangles = Ts;obj.GetComponent<MeshFilter>().mesh = mesh;// Step 5: 載入材質資源,添加給目標對象Material m = Resources.Load<Material>("M");obj.renderer.sharedMaterial = m;}}
后記:
形狀不是嚴格的麥比烏斯環,渲染只渲染了一面,目前沒有加法線和切線。
總結
以上是生活随笔為你收集整理的【Unity】Mesh网格编程(四)麦比乌斯环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: signature=380a93506d
- 下一篇: 计算机网络实验【路由器的基本配置】