c# - Unity C# - 在一个点周围随机生成游戏对象

标签 c# unity3d instantiation gameobject

我不确定如何解决这个问题,或者是否有任何内置的 Unity 函数可以帮助解决这个问题,因此不胜感激。

这是一张有助于描述我想做的事情的图片: enter image description here

我想在设定半径范围内的给定点周围生成游戏对象。然而,它们在这个半径中的位置应该是随机选择的。该位置应与原点(在地面上)具有相同的 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/

相关文章:

c# - 在C#中使用正则表达式来匹配rtf格式的文本

c# - 如何在 C# 上创建网络 map ?

c# - 使用 WMI 删除远程服务器上的文件

c# - foreach 中的 LabelFor()

ruby-on-rails - 解析从 Unity 发送到 Ruby On Rails 的 JSON POST 数据

c# - 该脚本缺少一个复选框

c++ - 无论如何,不​​是为 DLL 显式实例化模板代码,而是以某种方式隐藏实现代码本身吗?

c# - 使用自定义着色器会导致黑色图像

c++ - 实例化后模板的特化?

java - Java中使用参数实例化变量