Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 245
Mayron Avatar asked Jul 21 '26 05:07

Mayron


1 Answers

For personal space you can use colliders to avoid overlapping.

For spawning in circle you can use Random.insideUnitSphere. You can modify your method as,

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

Hope this helps you.

like image 149
Hamza Hasan Avatar answered Jul 22 '26 18:07

Hamza Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!