Generating random points and instantiating prefabs with a set distance
Hello Everyone.
I am working on a game where the player is able to run around a sphere. (a tiny planet if you will), this is working quite well and I am now looking into randomly generating these planets so there can be some variety.
void GenerateObjects()
{
currentPrefab = treePrefab;
string holderName = "Generated Objects";
if (transform.Find(holderName))
{
DestroyImmediate(transform.Find(holderName).gameObject);
}
Transform holder = new GameObject(holderName).transform;
holder.parent = transform;
objectCount = 0f;
while (objectCount < maxObjects)
{
Vector3 randomPoint = Random.onUnitSphere * planetSize / 10;
Transform obj = Instantiate(treePrefab, randomPoint, Quaternion.identity).transform;
obj.name = "Tree " + objectCount;
obj.parent = holder;
Vector3 gravityUp = (obj.position - transform.position).normalized;
Vector3 localUp = obj.transform.up;
obj.rotation = Quaternion.FromToRotation(localUp, gravityUp) * obj.rotation;
objectCount++;
}
}
In the code above I generate random points, Instantiate the prefabs and rotate them so that they are faced the right way up on the sphere. the only downside here is that the objects tend to overlap. I've tried many 'solutions' to this so far but to no avail. Very often it ends up in my unity crashing due to it running into an infinite loop when it comes to generating random points.
(just a minor example, there are also cases where its fully inside a previously instantiated object.
I hope someone can help me with this! Thanks!