- Home /
Problem with random generated objects(intersects objects)
Hello! I apologize for my terrible English, but I have the important question.
I have a problem. When generating facilities, some of them - cross each.How to fix it?
public int maxSisePoint = 25;
public int minSizePont = 15;
GameObject[] InstanceList;
public int SizePoint;
void Start (){
int SizePoint = Random.Range(minSizePont,maxSisePoint);
InstanceList = new GameObject[SizePoint];
for (int i = 0; i < SizePoint; i++){
int addXPos = Random.Range(-200, 200);
int addZPos = Random.Range(-200, 200);
GameObject item = Instantiate(Resources.Load("_Prefabs/prefab_CubePoint")) as GameObject;
item.transform.parent = transform;
InstanceList[i] = item;
InstanceList[i].transform.Translate(addXPos, 0, addZPos);
InstanceList[i].name= ""+(i+1);
}
}
Tried to check it, but does not work when it should.
for (int j = 0; j < InstanceList.Length; j++){
for (int i = 1; i< InstanceList.Length; i++){
if (InstanceList[j].renderer.bounds.Intersects(InstanceList[i].renderer.bounds)&i != j)
Debug.Log("* What is there to do? *");
}}
Help me pls!
The brute force approach to this problem is that you would repeatedly move the currently placed object until you find a position in which the bounds did not intersect. Note usually you limit the number of tries to some fixed number, since the possibility exists that there is no position that would work (and you don't want your program to hang).
Answer by robertbu · Jun 05, 2013 at 05:26 PM
I would restructure the code something like this:
using UnityEngine;
using System.Collections;
public class Bug20 : MonoBehaviour {
public int maxSisePoint = 25;
public int minSizePont = 15;
GameObject[] InstanceList;
private int created = 0;
public int SizePoint;
void Start () {
int SizePoint = Random.Range(minSizePont,maxSisePoint);
InstanceList = new GameObject[SizePoint];
for (int i = 0; i < SizePoint; i++){
GameObject item = Instantiate(Resources.Load("_Prefabs/prefab_CubePoint")) as GameObject;
item.transform.parent = transform;
Vector3 v3Org = item.transform.position;
for (int j = 0; j < 100; j++) {
item.transform.position = v3Org;
int addXPos = Random.Range(-200, 200);
int addZPos = Random.Range(-200, 200);
item.transform.Translate(addXPos, 0, addZPos);
if (BoundsCheck(item.renderer.bounds))
break;
}
InstanceList[i] = item;
InstanceList[i].name= ""+(i+1);
created++;
}
}
bool BoundsCheck(Bounds bounds) {
for (int i = 0; i < created; i++){
if (bounds.Intersects(InstanceList[i].renderer.bounds))
return false;
}
return true;
}
}
The code tries 100 times to position an object so that it does not intersect. I've never used the bound.intersect in this way. You may have to go to a model where objects are not placed within a certain radius of each other. Also there are several places in this code where I would do things differently, but since I don't know what you are doing, I did not want to make too many changes.