Unity C# - 在一个点周围随机生成GameObject

May*_*ron 3 c# instantiation unity-game-engine gameobject

我不知道如何处理这个问题或者是否有任何内置的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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢您提供任何建议!

Mic*_*sst 6

要在圆内生成对象,您可以定义生成圆的半径,并仅在-radius和radius之间向生成器的位置添加随机数,如下所示:

float radius = 5f;
originPoint = spawner.gameObject.transform.position;
originPoint.x += Random.Range(-radius, radius);
originPoint.z += Random.Range(-radius, radius);
Run Code Online (Sandbox Code Playgroud)

为了检测生成点是否接近另一个游戏对象,如何检查它们之间的距离是这样的:

if(Vector3.Distance(originPoint, otherGameObject.transform.position < personalSpaceRadius)
{
    // pick new origin Point
}
Run Code Online (Sandbox Code Playgroud)

我对unity3d不够熟练,所以也许不是最好的答案^^

另外

要首先检查哪些游戏对象位于生成区域中,可以使用此处定义的Physics.OverlapSphere函数:http : //docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html


Ham*_*san 6

对于个人空间,您可以使用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)));
    }
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助.