在一个球体上均匀分布多个prefab。方法:
球面上坐标满足x2+y2+z^2=R。以y轴向上为例
x = R * sin(alpha)cos(beta);
y = R * cos(alpha);
z = R * sin(alpha)sin(beta);
在unity实现:
public class DistributeLight : MonoBehaviour
{
// Use this for initialization
public GameObject prefab;
public int alphaStep = 12;
public int betaStep = 4;
public float R = 5.0f;
float Deg2Rad (float angle)
{
float rad = angle * Mathf.PI * 2 / 360;
return rad;
}
void CaculateSpherePosition ()
{
float alpha = 360.0f/alphaStep;
float beta = 360.0f/betaStep;
List<Vector3> posList = new List<Vector3> ();
posList.Clear ();
for (float i = 0.0f; i < 90.01f; i = i + alpha)
{
if (i == 0.0f)
{
Vector3 p = new Vector3 (0.0f, R, 0.0f);
posList.Add (p);
continue;
}
float R2 = R * Mathf.Sin (Deg2Rad (i));
for (float j = 0.0f; j < 360.0f; j = j + beta)
{
Vector3 p = new Vector3 (R2 * Mathf.Cos (Deg2Rad (j)), R * Mathf.Cos (Deg2Rad (i)), R2 * Mathf.Sin (Deg2Rad (j)));
posList.Add (p);
}
//step += 4;
}
int ii = 0;
foreach (Vector3 pos in posList)
{
GameObject temp = Instantiate (prefab) as GameObject;
temp.name = temp.name + ii;
ii++;
temp.transform.localPosition = pos;
temp.transform.LookAt (new Vector3 (0, 0, 0));
Debug.Log (pos);
}
}
void Start ()
{
CaculateSpherePosition ();
}
// Update is called once per frame
void Update ()
{
}
结果长这样: