I have an Empty gameObject that creates 20 objects at the start of the game.
var houses:Array = new Array();
var hs:Transform;
function Start ()
{
for(var a:int = 0; a < 20; a++)
{
ex = Random.Range(-200, 201);
zee = Random.Range(-200, 201);
newPos = Vector3(ex, 400, zee);
newhs = Instantiate(hs, newPos, transform.rotation);
houses.Push(newhs);
}
}
How can I make sure that all of the objects are a certain distance from each other?
I know it probably involves a for-loop inside the initial for-loop to check the distances. Anyone have an example script? Or an idea of what i can do? Thanks
You could create a function that draws a new location and check the neighborhood: if there are other objects closer than minDistance, draw another position, otherwise return the new position. For instance:
var houses:Array = new Array();
var hs:Transform;
var minDistance: float = 30;
var size: float = 200;
function FindNewPos(): Vector3 {
do {
// draw a new position
var newPos = Vector3(Random.Range(-size, size), 400, Random.Range(-size, size));
// get neighbours inside minDistance:
var neighbours: Collider[] = Physics.OverlapSphere(newPos, minDistance);
// if there's any neighbour inside range, repeat the loop:
} while (neighbours.length > 0);
return newPos; // otherwise return the new position
}
function Start (){
for(var a:int = 0; a < 20; a++){
var newPos = FindNewPos();
newhs = Instantiate(hs, newPos, transform.rotation);
houses.Push(newhs);
}
}
There’s a problem, however: Physics.OverlapSphere returns any colliders that touch the sphere - even the terrain, if it’s inside the range. If there are other objects that must be ignored, set the house prefab layer to 8, for instance, and use a layer mask in OverlapSphere:
var neighbours: Collider[] = Physics.OverlapSphere(newPos, minDistance, 1<<8);
This way, only the houses are counted.
Make another Vector3 variable for the last position used then use a if statement attached to a Vector3.distance or sqrmagnitude. If the result is lower then the desired distance make the if statement ignore it and re randomize the position. As CD said though I would use a while loop then said after x number of items have been made stop.
var houses:Array = new Array();
var hs:Transform;
var spawnAmount : int = 20;
var distance : float = 5;
private var spawnCount : int = 0;
private var isGood : boolean = false;
function Start ()
{
while ( spawnCount < spawnAmount ){
ex = Random.Range(-200, 201);
zee = Random.Range(-200, 201);
newPos = Vector3(ex, 400, zee);
for( var i in houses ){
//If new position is too close, don't bother with this random position
if( Vector3.Distance(i.position, newPosition) < distance)
isGood = false;
break
else
isGood = true;
}
if(isGood){
spawnCount++;
newhs = Instantiate(hs, newPos, transform.rotation);
houses.Push(newhs);
}
}
}
Hoping that it works, but this is the idea. Check that the random coordinates is valid, if it isn’t don’t bother creating and wait for loop to start over to get new coordinates. If coordinates are good then create object, store into list, and increase spawn counter. This code is not test.
Here is a quick take on the problem using a brute force approach. It generates a list of positions first and then creates the objects. The code repeatedly tries to find random values for a position (up to iMaxTries) that meet the distance criteria. If it fails, it bails out and then creates objects for positions that succeeded. For any reasonable settings of fMinDist and range of x and z values, it will almost always succeed in creating all 20. It is in C#.
void RandomGenerate() {
Vector3 v3T = Vector3.zero;
Vector3[] arv3 = new Vector3[20];
float fMinDist = 10.0f; // Minimum distance they need to be apart
int iMaxTries = 1000; // Number of times to try to generate a position
float fMinTry = Mathf.Infinity;
int i;
for (i = 0; i < 20; i++) {
for (int j = 0; j < iMaxTries; j++) {
v3T.x = Random.Range (-100.0f, 100.0f);
v3T.z = Random.Range (-100.0f, 100.0f);
fMinTry = Mathf.Infinity;
for (int k = 0; k < i; k++)
fMinTry = Mathf.Min ((v3T - arv3[k]).magnitude, fMinTry);
if (fMinTry > fMinDist) // Far enough apart
break;
}
if (fMinTry < fMinDist) {
Debug.Log ("Generation failed -- only found " + i + " points");
break;
}
arv3 *= v3T;*
-
}*
-
for (int j = 0; j < i; j++) {*
-
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);*
-
go.transform.position = arv3[j];*
-
}*
}
This is my take on it. I created an area on which objects are meant to spawn. I made it draw the radiuses and the spawn area of the “houses”. Something to note is that whatever object you declare as “House” must have a boolean as a property to keep track of it’s spawn status and draw the gizmos accordingly.
This spawner in particular spawns houses every frame and repeats. So it’s easy to visualize frame by frame within the editor
C#
Not perfect but works!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HouseSpawner : MonoBehaviour
{
public House housePrefab;
public int spawnQuantity = 10;
public static List<House> Houses = new List<House>();
[Range(0.01f, 2)]
public float toleranceRadius = 1.0f;
public Vector3 size = new Vector3(1,1,1); //The area on which we can spawn.
bool cooldown = false;
void Start()
{
House newHouse;
for (int i = 0; i < spawnQuantity; i++)
{
newHouse = (House)Instantiate(housePrefab, Vector3.zero, Quaternion.identity);
Houses.Add(newHouse);
}
}
private void LateUpdate()
{
if (!cooldown)
StartCoroutine(AutoRespawner());
}
IEnumerator AutoRespawner() {
cooldown = true;
foreach (var house in Houses) {
house.transform.position = new Vector3();
house.placedByForce = false;
}
foreach (var house in Houses)
{
house.transform.position = FindNewPos(ref house.placedByForce);
yield return null;
}
cooldown = false;
}
public Vector3 FindNewPos(ref bool placedByforce)
{
Vector3 newPos = new Vector3();
int neighbours = 0;
int searchLimit = 60;
int i = 0;
Collider[] results = new Collider[spawnQuantity];
do {
if (i >= searchLimit)
{
Debug.Log("Placed by force.");
placedByforce = true;
break;
}
newPos = transform.position + new Vector3(Random.Range(-size.x / 2, size.x / 2), 0, Random.Range(-size.z / 2, size.z / 2));
neighbours = Physics.OverlapSphereNonAlloc(newPos, toleranceRadius, results, 1 << 9);
i++;
} while (neighbours > 0);
// This loop doesn't guarantee 100% success,
// so be mindful of the size of the colliders
// being used and the searchLimit and toleranceRadius.
return newPos;
}
void OnDrawGizmosSelected()
{
if (Houses.Count > 0)
{
foreach (var house in Houses)
{
Gizmos.color = new Color(1, 1, 0, 0.5f);
if (house.placedByForce)
Gizmos.color = new Color(1, 0, 0, 0.5f);
// Draw a line depicting the tolerance radius.
Debug.DrawLine(house.transform.position, (toleranceRadius * house.transform.forward) + house.transform.position, Gizmos.color, 0);
// Draw a sphere depicting the tolerance bubble.
Gizmos.DrawSphere(house.transform.position, toleranceRadius);
}
}
Gizmos.color = new Color(1, 1, 1, 0.5f);
// Draws the area on which objects can spawn on.
Gizmos.DrawCube(transform.position, new Vector3(size.x, 1, size.z));
}
}