Unity用Mesh画多边形、圆形

首先贴上效果图
Unity用Mesh画多边形、圆形_第1张图片
Unity用Mesh画多边形、圆形_第2张图片
上面两个图就是使用Unity的Mesh画出的正五边形和正八变形。

无论是研究过Mesh还是只是有所听说,应该都听过网格,上面两个图形就是利用来网格的特性来实现的。

首先讲一下Mesh原理
无论渲染什么图形,就需要用到mesh将图形的形状展示出来,Unity中所有图形都是三角面组成,例如一个正方形
Unity用Mesh画多边形、圆形_第3张图片
一个正方形是由定点组成的两个三角片组成(三角形a和b),012组成三角形a,023组成三角形b,由此组成了一个正方形。注意,三角形的三个顶点排列必须是顺时针,如果是逆时针,在反面才会看到。

多边形也是类似原理,如图Unity用Mesh画多边形、圆形_第4张图片
代码

	public Button DrawPolygonButton;
	public InputField countInput;
	[HideInInspector]
	public GameObject drawGo;

	[HideInInspector]
	public MeshFilter meshFilter;

	[HideInInspector]
	public MeshRenderer meshRenderer;

	int count;

	void Awake(){
		DrawPolygonButton.transform.GetChild (0).GetComponent ().text = "DrawPolygon";
		DrawPolygonButton.onClick.AddListener (DrawPolygon);
	
		countInput.onValueChanged.AddListener ((string a) => {
			if (!string.IsNullOrEmpty(a)){
				count = System.Convert.ToInt32(a);
			}
		});
	}

	Mesh PrepareMesh(){
		drawGo = new GameObject ("DrawWithMesh");
		drawGo.transform.SetParent (transform);
		drawGo.transform.localPosition = Vector3.zero;
		drawGo.transform.localScale = Vector3.one;

		meshRenderer = drawGo.AddComponent ();
		meshRenderer.material = mat;

		meshFilter = drawGo.AddComponent ();
		Mesh mesh = meshFilter.mesh;
		mesh.Clear();

		return mesh;
	}

	void DrawPolygon(){
		int circle_count = count;
		Mesh mesh = PrepareMesh ();
		Vector3[] vertices = new Vector3[circle_count + 1];
		vertices[0] = Vector3.zero;
		float pre_rad = Mathf.Deg2Rad * 360 / circle_count;
		for (int i = 0; i < circle_count; i++) {
			float deg = -i * pre_rad;
			float x = Mathf.Cos (deg);
			float y = Mathf.Sin (deg);
			vertices [i + 1] = new Vector3 (x, y, 0) * 3;
		}
		mesh.vertices = vertices;	

		int[] triangles = new int[circle_count * 3];
		for (int i = 0; i < triangles.Length; i+=3) {
			int first = 0;
			int second = i / 3 + 1;
			int third = second + 1;
			if (third > circle_count) {
				third = 1;
			}
			triangles [i] = first;
			triangles [i + 1] = second;
			triangles [i + 2] = third;
		}
		mesh.triangles = triangles;
	}

如果要画圆形,则适量增加count数量就行

其他

更多Blog请见:https://yiyuan1130.github.io/
Github地址:https://github.com/yiyuan1130

你可能感兴趣的:(Unity3D,技术分享)