Search code examples
c#unity-game-engineinstantiationgameobject

Unity C# - Spawning GameObjects randomly around a point


I am not sure how to approach this problem or whether there are any built in Unity functions that can help with this problem so any advice is appreciated.

Here is an image that'll help describe what I want to do: enter image description here

I want to spawn Game Objects around a given point within the limits of a set radius. However their position in this radius should be randomly selected. This position should have the same Y axis as the origin point (which is on the ground). The next main problem is that each object should not clash and overlap another game object and should not enter their personal space (the orange circle).

My code so far isn't great:

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)));
    }
}

Thank you for any advice you can offer!


Solution

  • For spawning the object within the circle, you could define the radius of your spawn circle and just add random numbers between -radius and radius to the position of the spawner like this:

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

    For detecting if the spawn point is to close to another game object, how about checking the distance between them like so:

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

    I'm not that skilled in unity3d, so sry for maybe not the best answer^^

    Also:

    To check which gameobjects are in the spawn area in the first place, you could use the Physics.OverlapSphere Function defined here: http://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html