首先,我们先在Unity中创建一个GameObject对象,先建一个Cube
第二步给Cube添加Mesh Collider组件
第三步就开始写我们的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public int n = 20; //分成20份
public float r = 5;
// Start is called before the first frame update
void Start()
{
Mesh mesh = new Mesh();
//每份的弧度
float ang = 2 * Mathf.PI / n;
List<Vector3> vertices = new List<Vector3>();
//圆心
vertices.Add(Vector3.zero);
List<int> triangles = new List<int>();
for (int i = 0; i < n / 2 + 1; i++)
{
float xr = Mathf.Sin(i * ang) * r;
float y = Mathf.Cos(i * ang) * r;
for (int j = 0; j < n; j++)
{
float x = Mathf.Sin(j * ang) * xr;
float z = Mathf.Cos(j * ang) * xr;
vertices.Add(new Vector3(x, y, z)); //顶点 准备绘制
if (j == n - 1)
{
float x0 = Mathf.Sin(0) * xr;
float z0 = Mathf.Cos(0) * xr;
vertices.Add(new Vector3(x0, y, z0)); //顶点 准备绘制
}
if (i < n / 2 && j < n)
{
triangles.Add(i * (n+1) + j);
triangles.Add(i * (n + 1) + j + 1);
triangles.Add((i + 1) * (n + 1) + j);
triangles.Add((i + 1) * (n + 1) + j);
triangles.Add(i * (n + 1) + j + 1);
triangles.Add((i + 1) * (n + 1) + j + 1);
}
}
}
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh = mesh;
}
// Update is called once per frame
void Update()
{
}
}
这样我们就能得到一个球体,用来做摇奖机等类似的功能。