我们首先要算好我们需要绘制的球体的各项数据:
然后去技术物体之间的关系:
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeshYuan : MonoBehaviour
{
public int segments = 32; // 圆形的分段数
void Start()
{
// 创建一个新的Mesh对象
Mesh mesh = new Mesh();
// 获取顶点数组、三角形索引数组和UV坐标数组
Vector3[] vertices = new Vector3[segments + 1];
int[] triangles = new int[segments * 3];
Vector2[] uv = new Vector2[segments + 1];
// 设置顶点数组
vertices[0] = Vector3.zero;
for (int i = 1; i <= segments; i++)
{
float angle = 2f * Mathf.PI * (float)i / segments;
vertices[i] = new Vector3(Mathf.Sin(angle), 0f, Mathf.Cos(angle));
}
// 设置三角形索引数组
for (int i = 0; i < segments; i++)
{
triangles[i * 3] = 0;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = (i + 1) % segments + 1;
}
// 计算并设置UV坐标数组
uv[0] = new Vector2(0.5f, 0.5f);
for (int i = 1; i <= segments; i++)
{
float angle = 2f * Mathf.PI * (float)i / segments;
uv[i] = new Vector2((Mathf.Sin(angle) + 1f) / 2f, (Mathf.Cos(angle) + 1f) / 2f);
}
// 将顶点数组、三角形索引数组和UV坐标数组赋值给Mesh对象
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uv;
// 获取MeshFilter组件,并将Mesh对象赋值给它
MeshFilter meshFilter = GetComponent<MeshFilter>();
meshFilter.mesh = mesh;
}
}