I'm making a game which has multiple planets. Now I want to randomly generate their position, so I need to make sure they aren't too close to each other so they don't collide, neither too far away from each other since you should be able to see them all.
Each planet has a radius, so the distance between each planet should be: it's own radius + the radius of any other planet + a small offset. Also it would be nice if they aren't too far away from each other, as close as possible.
I just start with placing the first planet at 0,0,0. Then the second is easy to calculate (just a random direction and then the distance). The third also is doable, though after that I'm stumped.
How can I make a start? I'm using Unity, so the position is a Vector3, and I'm working in C#.
I don't use unity, but I think this problem isn't unity/c# specific.
You can implement it considering that every planet you want to place "depends" from a parent, some way, sun excluded and placed at origin.
So said, sun it's located at (0,0,0), Planet1 belongs from sun and it's located at certain radius distance, so it has its own radius and a rotation angle (always related to its parent). Planet 2 may have sun as parent, so it's a "planet", or from Planet1, becoming its moon. And so on...
With this simple scheme, you always have to manage 4 things which can be easily implemented as a class, i.e (not tested, I wrote it here without a compiler, check it from possible syntax errors):
public class Planet
{
public Planet Parent; //if null, I'm the first in chain
public float OrbitRadius; //From my parent
public float OrbitAngle; //0-360 around my parent
public float Radius; //Planet size
//EDIT:
public Vector3 Position;
public void CalculatePosition()
{
if(Parent == null) this.Position = new Vector(0, 0, 0);
this.Position = Parent.Position + OrbitRadius + Math.Sin(OrbitAngle * Math.PI / 180.0f); //Check if it has to be done for each vector component
}
}
More, you can easily implement sun, planets, moons, moons of moons :-)
Every time you create a planet, you will assign its parent, randomize class values taking care only of OrbitRadius >> Radius (>> I mean "really greater", not just "greater").
This should also give you a strongest "planet chain" to deal with, maybe with recursive functions.
As final step, you can "render" their positions walking all the chain, going to add PlanetX position to parent's position(s) in an incremental manner, dealing only to OrbitAngle; you need some Sin/Cos math here but you will not lose with scale factors.
I added a sort of CalculatePosition, can't verify it now, It's only there to clarify the concept and can be surely improved.