前言:
Unity3D中Mesh的基本單位是三角形,而圓形就是由許許多多的三角形組成的。那么我們就知道了繪制圓形的Mesh需要兩個變量:圓的半徑 以及分割數;
一、實現過程
基本過程與之前的類似,最基本的依然是頂點以及三角形索引數組,即:我們需要根據圓的半徑以及預備的分割數,通過算法得到:頂點的Vector3數組 以及對應的三角形索引數組;
1、基本的程序實現架構如下:
using UnityEngine; [RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))] public class yuan : MonoBehaviour { public float Radius = 6; //半徑 public int Segments = 60; //分割數 private MeshFilter meshFilter; void Start() { meshFilter = GetComponent<MeshFilter>(); meshFilter.mesh = CreateMesh(Radius, Segments); } Mesh CreateMesh(float radius, int segments) { Mesh mesh = new Mesh(); return mesh; } }
2、接下來就需要實現CreateMesh()函數的基本功能(下述的程序包含該函數功能的實現);整個程序的代碼如下:
using UnityEngine; [RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))] public class yuan : MonoBehaviour { public float Radius = 6; //半徑 public int Segments = 60; //分割數 private MeshFilter meshFilter; void Start() { meshFilter = GetComponent<MeshFilter>(); meshFilter.mesh = CreateMesh(Radius, Segments); } Mesh CreateMesh(float radius, int segments) { //vertices: int vertices_count = Segments + 1; Vector3[] vertices = new Vector3[vertices_count]; vertices[0] = Vector3.zero; float angledegree = 360.0f; float angleRad = Mathf.Deg2Rad * angledegree; float angleCur = angleRad; float angledelta = angleRad / Segments; for(int i=1;i< vertices_count; i++) { float cosA = Mathf.Cos(angleCur); float sinA = Mathf.Sin(angleCur); vertices[i] = new Vector3(Radius * cosA, 0, Radius * sinA); angleCur -= angledelta; } //triangles int triangle_count = segments * 3; int[] triangles = new int[triangle_count]; for(int i=0,vi=1;i<= triangle_count-1;i+=3,vi++) //因為該案例分割了60個三角形,故最后一個索引順序應該是:0 60 1;所以需要單獨處理 { triangles[i] = 0; triangles[i + 1] = vi; triangles[i + 2] = vi + 1; } triangles[triangle_count - 3] = 0; triangles[triangle_count - 2] = vertices_count - 1; triangles[triangle_count - 1] = 1; //為了完成閉環,將最后一個三角形單獨拎出來 //uv: Vector2[] uvs = new Vector2[vertices_count]; for (int i = 0; i < vertices_count; i++) { uvs[i] = new Vector2(vertices[i].x / radius / 2 + 0.5f, vertices[i].z / radius / 2 + 0.5f); } //負載屬性與mesh Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.uv = uvs; return mesh; } }
3、效果圖:
碰到的小知識:
【歡迎轉載】
轉載請表明出處: 樂學習