- Home /
Instantiate gameobject with minimum distance from another gameobject
Hi guys, I should instantiate a series of objects but always leaving a minimum distance between them otherwise they go into overlap. Any suggestion?
public void spawn() {
Vector3 pos = center + new Vector3(Random.Range(-size.x , size.x),Random.Range(-15,-25) , Random.Range(size.z , size.z / 2));
CuboCount = Instantiate(cuboprefab, pos, randomRotation) as GameObject;
Destroy(CuboCount, 30f);
CuboCount.transform.SetParent(Cubofolder.transform);
GameObject aereo = GameObject.Find("Main");
`
Answer by Kennai · Jun 10, 2019 at 09:41 AM
Hey, @mustang4484 ! How about to use matrix of whole numbers? Lets say, you have matrix 15 x 15 x 5. its a whole numbers. You create same matrix as an array of array of array. once you spawn your object, you can assign random position in that matrix + random position inside matrix. I mean - you get random position (3,6,2). then you add small random values to, but so that your object wont exceed matrix cell volume. it's like add "small" noise to position - maybe random of 0.2f to each value so you may have position (3.1f , 5,57f ,1,8f) then you set in your array that position (3,6,2) is busy.
when you will generate new spawn position, you will need to count, how many objects already is spawned in same row and same column and same height and decrease random by that value for eaxh axis.
About how to get random position: For better view, represent your matrix as a long long row., where 0 is free, 1 is busy position. Lets say, we have row with 10 positions: (0, 0, 0, 1, 1, 0, 1, 0, 0, 1) - it has already 4 other spawned objects of max 10 positions. Now you need to generate new random position. How to do it:
max value is 10 here
you already have 4 spawned objects, so you may have max = 10-4 = 6 new positions.
get random value of 6 - let it be 3 - generated value.
now start your loop until generated value is below zero.
check each cell, if cell is free - decrease generated value. if cell is busy, go to next cell.
once generated value is zero - you got your index position. in this example it would be (0, 0, 0, 1, 1, >1<, 1, 0, 0, 1). Position marked as >1<
its a 5 index, lets say it means 5f (but in your way, you will need to convert this value into matrix position, like (x,y,z)). then you add "small" noise - random of 0.2f to each axis and done.
Your answer
![](https://koobas.hobune.stream/wayback/20220612202927im_/https://answers.unity.com/themes/thub/images/avi.jpg)