Trying to instantiate many objects - without overlapping

I’m making an endless runner, with objects instantiating at random points on my terrain. However, some of the objects are instantiating overtop of each other.

I have a hunch this might have something to do with the physics not being updated between instatiations (which are all happening in the same frame).

The prefabs being instantiated all have the tag “PlaceableObject” and a collider.

    public void Place() {
        int numObjects = Random.Range(TerrainController.MinObjectsPerTile, TerrainController.MaxObjectsPerTile);
     
        for (int i = 0; i < numObjects; i++)
        {
            int prefabElement = ChooseObject();
            Vector3 startPoint = RandomPointAboveTerrain();
            RaycastHit hit;
            if (Physics.Raycast(startPoint, Vector3.down, out hit) && hit.collider.CompareTag("Terrain"))
            {
                Quaternion orientation = Quaternion.Euler(Vector3.up * Random.Range(0f, 360f));
                RaycastHit boxHit;
                if (Physics.BoxCast(startPoint, TerrainController.PlaceableObjects[prefabElement].size, Vector3.down, out boxHit, orientation) && boxHit.collider.CompareTag("Terrain"))
                {
                    Vector3 placementPosition = new Vector3(startPoint.x, hit.point.y, startPoint.z);
                    Instantiate(TerrainController.PlaceableObjects[prefabElement].gameObject, placementPosition, orientation, placedObjectsParent);                   
                }
            }
        }
    }

Any ideas?

Maybe try to create an array of positions first and check while adding new random pos if they already exist, if yes, skip and try a new one until your array count reached your desired pos count

1 Like

That’s an interesting idea! I’ll ponder this.
I’ve since come upon this video by Sebastian Lague, which suggests something very similar to what you’re suggesting.

I only wish he got around to doing Part 2, in which he explains how he does items of different radiuses.