【发布时间】:2022-01-18 21:30:22
【问题描述】:
我正在编程一个随机的"Stone" Spawner,目前有一个大问题。我有一些解决方法的想法,但想知道一种性能友好的方法。
所以我去Spawn the Objects on the Sphere Surface 的方式是这样的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnObjects : MonoBehaviour
{
public Vector3 centerOfSphere = new Vector3(0, 5000, 0);
public float radiusOfSphere = 5000.0f;
public List<GameObject> stones;
public int stonesToSpawn = 1;
void Start()
{
Vector3 center = transform.position + centerOfSphere; //Setting the center position of the Sphere
//This for loop is spawning the Stones on a random position on Sphere Surface
for (int i = 0; i < stonesToSpawn; i++)
{
Vector3 pos = RandomCircle(center, radiusOfSphere);
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, center - pos);
Instantiate(stones[Random.Range(0, stones.Count)], pos, rot);
}
}
//Method returns a Random Position on a Sphere
Vector3 RandomCircle(Vector3 center, float radius)
{
float alpha = UnityEngine.Random.value * 360;
float beta = UnityEngine.Random.value * 360;
Vector3 pos;
pos.x = radius * Mathf.Cos(beta) * Mathf.Cos(alpha);
pos.y = radius * Mathf.Cos(beta) * Mathf.Sin(alpha);
pos.z = radius * Mathf.Sin(beta);
return pos;
}
}
非常感谢您的以下解释! :)
【问题讨论】:
-
物体的中心应该是从 z 轴偏离 -90 到 +90 度的随机角度,然后围绕 z-zxis 从 0 到 360 度随机旋转..
-
@derHugo 哈哈哈,你以前去过哪里?我花了大约 10 个小时试图找到正确的公式来获得球面上的随机点:D