首先用Mesh画出球
RequireComponent(组件) 在脚本添加时 为你附带组件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshCollider))]
[RequireComponent(typeof(MeshRenderer))]
public class Ball : MonoBehaviour
{
//球的层数
int m = 30;
//半径
int r = 5;
//弧度
float red;
List<Vector3> verticas = new List<Vector3>();
List<int> triangles = new List<int>();
Mesh mesh;
List<GameObject> spheres= new List<GameObject>();
void Start()
{
mesh = new Mesh();
//求出球的弧度
red = Mathf.PI * 2 / m;
CreateBall();
AddSphere();
}
void Update()
{
}
//生成小球的函数
public void AddSphere()
{
for (int i = 0; i < 10; i++)
{
Vector3 pos = Random.insideUnitSphere * 5;
GameObject go = Instantiate(Resources.Load<GameObject>("Sphere"));
go.transform.localEulerAngles = Vector3.zero;
go.transform.localScale = Vector3.one;
go.transform.localPosition = transform.position+pos;
spheres.Add(go);
}
}
public void CreateBall()
{
for (int i = 0; i < m / 2 + 1; i++)
{
//求出每层圆的半径
float xr = Mathf.Sin(i * red) * r;
//求出每层的高度
float y = Mathf.Cos(i * red) * r;
for (int j = 0; j < m; j++)
{
float x1 = Mathf.Sin(j * red) * xr;
float z = Mathf.Cos(j * red) * xr;
verticas.Add(new Vector3(x1, y, z));
//判断是否为最后一次
if (j == m - 1)
{
//将第一个坐标再添加到最后
float x2 = Mathf.Sin(0) * xr;
float z2 = Mathf.Cos(0) * xr;
verticas.Add(new Vector3(x2, y, z2));
}
if (i < m / 2-1 && j < m)
{
triangles.Add(i * (m + 1) + j);
triangles.Add(i * (m + 1) + j + 1);
triangles.Add((i + 1) * (m + 1) + j);
triangles.Add((i + 1) * (m + 1) + j);
triangles.Add(i * (m + 1) + j + 1);
triangles.Add((i + 1) * (m + 1) + j + 1);
}
}
}
mesh.vertices = verticas.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh = mesh;
Material mat = new Material(Shader.Find("Standard"));
mat.color = Color.green;
GetComponent<MeshRenderer>().material = mat;
}
}
创建物理材质
把物理材质的静动态摩擦设置为0 把反弹力(Bounciness)设置为1
把物理材质分别给大球和小球
以下为实现的效果: