hello i have a random generation script that random generates all the structures and the world. But sometimes the structures collide with each other, (spawning inside of each other). How do i prevent this?
Thanks
here is one of my random generation scripts:
using UnityEngine;
using System.Collections;
public class GenerateTrees2 : MonoBehaviour
{
//HouseDetails
public GameObject Tree;
public int z;
public int x;
public int SpawnTimer = 30;
public int rotationY;
public int rotationZ;
public Quaternion randomRotation;
void Start ()
{
while (SpawnTimer > 0)
{
//RandomRotation
int rotationZ = Random.Range(-500, 500);
int rotationY = Random.Range(-500, 500);
int rotationX = 0;
//RandomPosition
int z = Random.Range (-75, 75);
int x = Random.Range (-75, 75);
int y = -2;
Vector3 housePosHere = new Vector3 (x, y, z);
//Rotation
randomRotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
//LastFixes
SpawnTimer--;
Instantiate (Tree, housePosHere, randomRotation);
}
}
}
Do something like this:
using UnityEngine;
using System.Linq;
public class GenerateTrees2 : MonoBehaviour
{
//HouseDetails
public GameObject Tree;
public int z;
public int x;
public int SpawnTimer = 30;
public int rotationY;
public int rotationZ;
public Quaternion randomRotation;
// Change this value to the desired detection radius
public float DetectionRadius = 1;
protected void Start()
{
// You do not want a while loop like this in your main thread, please make use of coroutines, as for the recursvie method beneath!
while (SpawnTimer > 0)
{
SpawnRandomTree();
}
}
protected void SpawnRandomTree()
{
//RandomPosition
int z = Random.Range(-75, 75);
int x = Random.Range(-75, 75);
int y = -2;
Vector3 housePosHere = new Vector3(x, y, z);
//Rotation
randomRotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
//LastFixes
SpawnTimer--;
// Make sure there is s "TreeScript" script attached to each Tree ;-)
RaycastHit[] hits = Physics.SphereCastAll(housePosHere, DetectionRadius, transform.up);
if (hits.FirstOrDefault(t => t.collider.GetComponent<TreeScript>()) == null)
{
Instantiate(Tree, housePosHere, randomRotation);
}
else
{
SpawnRandomTree();
}
}
}