簡體   English   中英

Unity C# - 在一個點周圍隨機生成GameObject

[英]Unity C# - Spawning GameObjects randomly around a point

我不知道如何處理這個問題或者是否有任何內置的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)));
    }
}

感謝您提供任何建議!

為了在圓圈內生成對象,您可以定義生成圓的半徑,只需將-radius和radius之間的隨機數添加到spawner的位置,如下所示:

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

對於個人空間,您可以使用colliders避免重疊。

對於在circle中生成,可以使用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)));
    }

希望這對你有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM