Randomly Place Cubes In Viewport Without Overlap

Hi all,

Been racking my brain on this for ages.

I want to randomly place cubes in the viewport, without them overlapping each other (but not based on pre-defined spawn points).

So first step was to randomise their position in the viewport.

Second step was to iterate through the collection of cube transforms and check the a potential random position is close to another others:

Two ways (both which haven’t worked are) to use a Physics.Overlap at the position to check if there are any colliders there (aka other cubes), if there are try and new position, if not rinse and repeat.

The other way was to check the potential random position and then check the magnitude between all other places buildings to see if you are close, if so do it again, if not place it down.

Both of these seemed good solutions, but the physics overlap seems a bit heavy and doesn’t seem to be returning any colliders (even though the cubes have box colliders) and then other solution, is 2 nested for loops, which (probably just my logic) don’t seem to be working.

Any help would be greatly appreciated.

My code so far:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BuildingManager : MonoSingleton<BuildingManager> {
	
	[SerializeField]
	Transform[] m_buildings;
	
	List<Vector3> placedBuildings = new List<Vector3>();
		
	//------------------------------------------------------------------------------------------------------
	
	void Awake()
	{		
		// Place initial building
		m_buildings[0].position = GetRandomTerrainPos(m_buildings[0]);
		
		m_buildings[0].position = new Vector3(m_buildings[0].position.x, 0f, m_buildings[0].position.z);
						
		placedBuildings.Add(m_buildings[0].position);
		
		// Place the other buildings
		// Start index at 1
		for(int i = 1, n = m_buildings.Length; i < n; i++)
		{	
			Transform t = m_buildings*;*
  •  	// Get a random position*
    
  •  	Vector3 randomPos = GetRandomTerrainPos(t);*
    
  •  	// Check if this position is near any others*
    
  •  	for(int j = 0, k = placedBuildings.Count; j < k; j++)*
    
  •  	{	*
    
  •  		// If the distance between the potential random position and*
    
  •  		// the placed building is more than 2f (magic number) place*
    
  •  		// the building there (this is a sutiable location)*
    
  •  		if((randomPos - placedBuildings[j]).magnitude > 2f)*
    
  •  		{*
    
  •  			t.position = randomPos;*
    
  •  			t.position = new Vector3(t.position.x, 0f, t.position.z);*
    
  •  			placedBuildings.Add(t.position);*
    
  •  		}*
    
  •  		// Else look for another location*
    
  •  		else*
    
  •  		{* 
    

// j–;

  •  		}*
    
  •  	}*
    
  •  }*
    
  • }*

  • //------------------------------------------------------------------------------------------------------*

  • Vector3 GetRandomTerrainPos(Transform t)*

  • {*

  •  return Camera.main.ViewportToWorldPoint(new Vector3(Random.value, Random.value, (Camera.main.transform.position.y - t.position.y) - 5f));*
    
  • }*
    }

You can fold it all into a single routine for performance, but unless you have a huge amount of buildings, I’ll pull the building check out into it own function:

bool FreeAndClear(Vector3 randomPos) {
	for(int i = 0, i < placedBuildings.Count; i++) {   
		if((randomPos - placedBuildings*).magnitude < acceptableDistance) {*
  •  	return false;*
    
  •  }*
    
  • }*
  • return true;*
    }
    Then your find a position code becomes:
    Vector3 randomPos;
    for (int m = 0; m < 1000; m++) {
    randomPos = GetRandomTerrainPos(t);
    if (FreeAndClear(randomPos))
    break;
    }
    // At this point you would have a valid position
    // or your code would have tried 1000 times to
    // find one and failed.
    Note you want to put the check in a ‘for’ loop so there is a termination condition. If you put the check in a ‘while(true)’ there is a chance that the code could never find an acceptable position and the app would hang.