Instantiating Objects randomly on a sphere with a set distance radius
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!
Your answer
Follow this Question
Related Questions
How do i Instantiate sub-Points with in Multiple Points?? 0 Answers
How do I Instantiate a prefab at the x axis position of where the UI button was clicked 1 Answer
How to fix snake behavior in Unity3d? 0 Answers
I'm having a few issues with (Catmull)Splines that i need help with. 1 Answer
Problem with Instantiate custom class 0 Answers