Hi guys! I wrote a script that create random planes at random positions colored randommly.
But, some of these planes overlap each other and I don’t want it. I would write a script that create random planes in random position but that don’t overlap them each other.
How can I do?
Here’s the script that I attached to my MainCamera.
#pragma strict
var s : GameObject;
var colors = [Color.red, Color.green, Color.blue];
function Start () {
StartCoroutine(creazione(1));
}
function Update () {
}
function creazione(tempo) {
while(true)
{
s = GameObject.CreatePrimitive(PrimitiveType.Plane);
s.renderer.material.color = colors[Random.Range(0, colors.Length)];
s.transform.position.y = 0;
s.transform.position.x = 0;
s.transform.position.z = Random.Range(0, 100);
yield WaitForSeconds(tempo);
}
}
I hesitate to answer since I’m fuzzy on your criteria. But here is a script. It works by keeping a list of the Transforms of the objects created. When a new position is selected, it tests that position against the existing positions. Since a plane is 10 x 10 units, if a position is less than 10 units from an existing position, then there will be an overlap. It tries 50 times to find a position that fits. If it fails, it bails out of the coroutine.
#pragma strict
import System.Collections.Generic;
var list : List.<Transform> = new List.<Transform>();
var s : GameObject;
var colors = [Color.red, Color.green, Color.blue];
function Start () { StartCoroutine(creazione(1)); }
function creazione(tempo) {
while(true) {
var pos : Vector3;
for (var i = 0; i < 50; i++) {
pos = Vector3(0f,0f,Random.Range(0,100));
if (!CheckOverlap(pos)) break;
}
if (CheckOverlap(pos)) break;
s = GameObject.CreatePrimitive(PrimitiveType.Plane);
s.renderer.material.color = colors[Random.Range(0, colors.Length)];
s.transform.position = pos;
list.Add(s.transform);
yield WaitForSeconds(tempo);
}
}
function CheckOverlap(pos : Vector3) {
for (var t : Transform in list) {
if (Vector3.Distance(t.position, pos) < 10.0)
return true;
}
return false;
}