- Home /
How can i randomly create an array of objects without colliding one another?
Hello again! I am trying to create a script that could come up with a number of randomly generated positions to place objects. How can i avoid having the objects collide with each other? I know how to DETECT a collision (using Physics.OverlapSphere or CheckSphere) but how would i apply this to this script?
This is what I know:
var count:int = 5;
var prefab:Transform;
///This will create an array of objects in random positions.
for(var i = 0; i < count; i++)
{
var randPos = Vector3(Random.Range(-10, 10), Random.Range(-10, 10), Random.Range(-10, 10));
newObj = Instantiate(prefab, transform.position, transform.rotation);
}
And just checking and repositioning the object isnt ideal either because it may never find a spot in the for-loop, which could crash unity. Anyone have any other approaches?
Do you have access to the size of the object ? if not, using gameObject.renderer.bounds.size gives you a vector 3 representing its size.
You could spawn them so you know they won't touch each other. ever.
EDIT- wait, I forgot about the random in this.
You could translate objects manually when they're in collision, until they are no more. The first point is totally random, if it hits something, then you push it aside until it's free.
Answer by zharik86 · Aug 15, 2014 at 07:10 PM
If you want use Physics.OverlapSphere and you objects have unique tag, for example, "mob", that here small example(write on CSharp):
public Transform myPrefab = null; //reference for your object
public float myRadius = 2.0f; //Radius of the sphere described round object
public int myCount = 5; //count created objects
void Awake() {
Vector3 randPos = Vector3.zero;
int myCheck = 0; //count overlap colliders
for(int i = 0; i < myCount; i++) {
do {
myCheck = 0;
randPos = Vector3(Random.Range(-10.0f, 10.0f), Random.Range(-10.0f, 10.0f), Random.Range(-10.0f, 10.0f));
Collider[] hitColliders = Physics.OverlapSphere(ramdPos, myRadius);
for(int j = 0; j < hitColliders.Length; j++) {
if (hitColliders[j].tag == "mob") {
myCheck++;
}
}
} while (myCheck > 0);
Transform newObj = (Transform) Instantiate(prefab, randPos, Quaternion.identity);
}
}
But at the wrong initial parameters at you the infinite cycle can study. Be attentive. I hope that it will help you.
I figured it out. I ended up with just about the same solution. Ive tweeked it a bit to avoid infinite cycles by adding an aborting function. Thanks bunches! :)
Your answer
Follow this Question
Related Questions
Spawn GameObjects without overlap 1 Answer
One of the numbers as Second ? 1 Answer
Instantiate object in random position inside a navmesh 1 Answer
Spawning different random objects at the same position? 2 Answers
Random array issue C# 2 Answers