我不确定如何解决这个问题,或者是否有任何内置的 Unity 函数可以帮助解决这个问题,因此不胜感激。
我想在设定半径范围内的给定点周围生成游戏对象。然而,它们在这个半径中的位置应该是随机选择的。该位置应与原点(在地面上)具有相同的 Y 轴。下一个主要问题是每个对象不应与另一个游戏对象发生冲突和重叠,也不应进入它们的个人空间(橙色圆圈)。
我的代码目前还不是很好:
public class Spawner : MonoBehaviour {
public int spawnRadius = 30; // not sure how large this is yet..
public int agentRadius = 5; // agent's personal space
public GameObject agent; // added in Unity GUI
Vector3 originPoint;
void CreateGroup() {
GameObject spawner = GetRandomSpawnPoint ();
originPoint = spawner.gameObject.transform.position;
for (int i = 0; i < groupSize; i++) {
CreateAgent ();
}
}
public void CreateAgent() {
float directionFacing = Random.Range (0f, 360f);
// need to pick a random position around originPoint but inside spawnRadius
// must not be too close to another agent inside spawnRadius
Instantiate (agent, originPoint, Quaternion.Euler (new Vector3 (0f, directionFacing, 0f)));
}
}
感谢您提供的任何建议!
最佳答案
对于个人空间,您可以使用colliders
来避免重叠。
对于圆形生成,您可以使用 Random.insideUnitSphere
。您可以将您的方法修改为,
public void CreateAgent() {
float directionFacing = Random.Range (0f, 360f);
// need to pick a random position around originPoint but inside spawnRadius
// must not be too close to another agent inside spawnRadius
Vector3 point = (Random.insideUnitSphere * spawnRadius) + originPoint;
Instantiate (agent, point, Quaternion.Euler (new Vector3 (0f, directionFacing, 0f)));
}
希望对你有帮助。
关于c# - Unity C# - 在一个点周围随机生成游戏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34675771/