Search Unity

Trying to instantiate many objects - without overlapping

Discussion in 'Scripting' started by HeyBishop, May 17, 2019.

  1. HeyBishop

    HeyBishop

    Joined:
    Jun 22, 2017
    Posts:
    238
    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.

    Code (CSharp):
    1.  
    2.     public void Place() {
    3.         int numObjects = Random.Range(TerrainController.MinObjectsPerTile, TerrainController.MaxObjectsPerTile);
    4.      
    5.         for (int i = 0; i < numObjects; i++)
    6.         {
    7.             int prefabElement = ChooseObject();
    8.             Vector3 startPoint = RandomPointAboveTerrain();
    9.             RaycastHit hit;
    10.             if (Physics.Raycast(startPoint, Vector3.down, out hit) && hit.collider.CompareTag("Terrain"))
    11.             {
    12.                 Quaternion orientation = Quaternion.Euler(Vector3.up * Random.Range(0f, 360f));
    13.                 RaycastHit boxHit;
    14.                 if (Physics.BoxCast(startPoint, TerrainController.PlaceableObjects[prefabElement].size, Vector3.down, out boxHit, orientation) && boxHit.collider.CompareTag("Terrain"))
    15.                 {
    16.                     Vector3 placementPosition = new Vector3(startPoint.x, hit.point.y, startPoint.z);
    17.                     Instantiate(TerrainController.PlaceableObjects[prefabElement].gameObject, placementPosition, orientation, placedObjectsParent);                  
    18.                 }
    19.             }
    20.         }
    21.     }
    22.  
    Any ideas?
     
  2. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    890
    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
     
    HeyBishop likes this.
  3. HeyBishop

    HeyBishop

    Joined:
    Jun 22, 2017
    Posts:
    238
    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.