我不确定如何解决这个问题,或者是否有任何内置的 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)));
}
希望这对您有帮助。
为了在圆圈内生成对象,您可以定义生成圆的半径,然后在 -radius 和 radius 之间添加随机数到生成器的位置,如下所示:
float radius = 5f;
originPoint = spawner.gameObject.transform.position;
originPoint.x += Random.Range(-radius, radius);
originPoint.z += Random.Range(-radius, radius);
为了检测生成点是否靠近另一个游戏对象,可以像这样检查它们之间的距离:
if(Vector3.Distance(originPoint, otherGameObject.transform.position < personalSpaceRadius)
{
// pick new origin Point
}
我对unity3d不太熟练,所以抱歉可能不是最好的答案^^
还有:
要首先检查哪些游戏对象位于生成区域中,您可以使用此处定义的Physics.OverlapSphere 函数: http://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
如何在 Unity 中生成游戏对象?很简单,用一个魔法咒语: 闭上眼睛,集中注意力,想象你想要生成的物体。喊出咒语“Unityus Spawnus Objectus!”点击手指观看更多详情 - https://www.youtube.com/watch?v=DKZEYIHU6r8 恭喜!你是一个能创造奇迹的巫师。