To build solar system generator, I need to make the planet to have an orbit and rotate in this orbit. The orbit of the planet usually ellipse and the orbit need to be generated randomly.

Also, the planet need to rotate in its axis, so we need a function to achieve this work.

To draw the orbit we use Line Renderer, to make a line for the orbit.

#### Build the Orbit and Orbit Line

``````public Transform orbitingObject;
public EllipseClass orbitPath;

LineRenderer lr;

[Range(3, 72)]
public int segments;

[Range(0f, 1f)]
public float orbitProgress = 0f;
public float orbitPeriod = 3f;
public float planetRotation = 1f;
public bool orbitActive = true;

void Start()
{
if (orbitingObject == null)
{
orbitActive = false;
return;
}
SetOrbitingObjectPosition();
StartCoroutine(AnimationOrbit());

}

private void Update()
{
orbitingObject.transform.Rotate(Vector3.up, planetRotation, Space.World);
}

void SetOrbitingObjectPosition()
{
Vector2 orbitPos = orbitPath.Evaluate(orbitProgress);
orbitingObject.localPosition = new Vector3(orbitPos.x, 0, orbitPos.y);

}

//make the planet move
IEnumerator AnimationOrbit()
{
if (orbitPeriod < 0.1f)
{
orbitPeriod = 0.1f;
}
float orbitSpeed = 0.1f / orbitPeriod;
while (orbitActive)
{
orbitProgress += Time.deltaTime * orbitSpeed;
orbitProgress %= 1f;
SetOrbitingObjectPosition();
lr = GetComponent<LineRenderer>();
CalculateEllipse();
yield return null;

}

}

//Build the orbit Line
void CalculateEllipse()
{
Vector3[] points = new Vector3[segments + 1];
for (int i = 0; i < segments; i++)
{
Vector2 position2D = orbitPath.Evaluate((float)i / (float)segments);
points[i] = new Vector3(position2D.x, 0f, position2D.y);
}
points[segments] = points[0];

lr.positionCount = segments + 1;
lr.SetPositions(points);
}``````

After finish this work, we need to generate the orbit randomly. To achieve this we need to avoid if the orbit will cross each other. Even though, in real life there is case like this. It would be better to avoid that in this case.

#### Randomly Generate Orbit

``````void setOrbit(string NameOfPlanet, int i)
{
if (disableOrbit)
{
GameObject.Find(NameOfPlanet).GetComponent<LineRenderer>().enabled = false;
}
GameObject.Find(NameOfPlanet).GetComponent<OrbitMotion>().orbitPath.xAxis = Random.Range((i+1)*60, ((i+1) * 60)+30);
GameObject.Find(NameOfPlanet).GetComponent<OrbitMotion>().orbitPath.yAxis = Random.Range((i + 1) * 60, ((i + 1) * 60) + 30);

GameObject.Find(NameOfPlanet).GetComponent<OrbitMotion>().orbitProgress = Random.Range(0.00f, 1.00f);
GameObject.Find(NameOfPlanet).GetComponent<OrbitMotion>().orbitPeriod = Random.Range(3, 15);
GameObject.Find(NameOfPlanet).GetComponent<OrbitMotion>().planetRotation = Random.Range(-1.00f, 1.00f);
}``````
(Visited 1,103 times, 1 visits today)