I'm making a 4x game with solar systems in the Unity game engine. I have planets which I'd like to orbit around their stars in an elliptical fashion. The planets for various reasons are not parented to the stars. The game is in 3D space with a top down view, so the orbits are on the x and z planes with a y of zero.
Following on from various posts e.g. this, this and this I've put together the following code in a co-routine:
while (true)
{
yield return new WaitForFixedUpdate();
x = orbitStar.position.x + ((dist + xMod) * Mathf.Sin(a));
z = orbitStar.position.z + (dist * Mathf.Cos(a));
orbitLines.position = new Vector3(x, 0, z);
a += aPlus * Time.fixedDeltaTime;
}
orbitStar
is the star the planets are orbiting, dist
is the distance to the star, orbitLines
is the object to be orbited (actually a trail renderer, later to also be the planet but in turn based time not real time) and xMod
is the variable that controls how elliptical the path is. a
and aPlus
are arbitrary variables that control the angular velocity.
This forms a nice ellipse based on xMod
. The problem is the trail renderer does not bisect the planet as xMod
is increased, the trail moves further away from the planet, here the trail is the turquoise color curve:
Being somewhat inept at maths I've tried juggling round the variables and throwing 'magic' numbers at the function with inconsistent results e.g:
z = orbitStar.position.z + ((dist - xMod) * Mathf.Cos(a));
and
z = orbitStar.position.z + (dist * Mathf.Cos(a)) + someOtherVariable;
How can I correct for the distance xMod
is moving the trail by, so that the trail moves through the planet?