I'm making a 2D game where you control a spaceship and fly between disk-formed planets of differing size (mass/pull). The planets are small and you can fly near several at once. I need to calculate the gravity produced by each of these planets pulling on the ship including the velocity of the ship.

I figured out a way to approximate it:

Calculate the position of the rocket in the next frame based on the angle and velocity

From this position, calculate the position of a point pulled towards the planet where the larger the planet, the further this point is towards said planet

Do this for each planet then average each of these points to find the new location for the rocket this frame

Rotation doesn't matter in my case, but I would calculate it by comparing this point's location and the previous point's location.

Repeat for every frame.

This may be a good approximation, and accuracy isn't a huge deal in my case, but I am wondering if there is a better way to do this with physics formulas. I haven't taken a physics class yet. The other main problem with this solution is that it must calculate it step by step or frame by frame. If there is a formula to do this the path could be calculated from the very start before.

1 Answer
1

The formula for gravity is $F_g=\large{\frac{Gm_1m_2}{r^2}}$. So store variables for your $x$ and $y$ velocities (or an array or whatever method you wish) and change your position by your velocity each frame. Also each frame, use a loop (I don't know what language you're using so I can't give exact code) to look at each planet and plug everything into the formula and change the velocity by the amount it returns, in the direction of the planet. Multiply/divide it by whatever you want to make it reasonable, unless you're using actual units, in which case, divide the number by the mass of the ship. Do this for every planet in the system.

About calculating beforehand, this is probably technically possible, but would take a ridiculous amount of math and might be more difficult (for the computer) than updating frame-by-frame. if there's one body, the trajectory isn't too hard to predict, though.