You must give the initial velocity of the planet v = (vx, vy, vz), tangent to the desired orbit. If the position of the sun is s, and the planet is p, then there is always a force acting between them: one on the planet points to the sun, vector t = (s - p) and vice versa. The magnitude of this force is g Ms Mp / (t dot t), where the “point” is the point product, g is the standard acceleration of gravity, and Ms, Mp are the corresponding masses.
If you are making a detailed model where all bodies can stretch all other bodies, then the algorithm must accumulate all paired forces in order to get a single resulting force vector acting on each body (planet or sun). Otherwise, you can agree to the approach, when only the sun pulls on planets and other forces, are considered too small to make a difference.
So the algorithm:
Choose dt, the time step, a small interval. Set initial positions and velocities (for planets, velocity is tangent to desired orbit. Sun has velocity zero.) loop Accumulate all forces on all bodies with current positions. For each body position=p, velocity=v, net resultant force=f, mass=m, update its velocity: v_new = v + f / m dt update position p_new = p + 0.5 * (v + v_new) v = v_new; p = p_new Render end loop
As already mentioned, Euler is simple, but requires a very small time step in order to obtain even reasonable accuracy. Sometimes you can introduce only a small part of the resistance in the system (multiply the speed by a factor just below 1) to maintain stability, if they otherwise explode.
source share