Question

So I'm trying to write a 2D space game in Java, and I'm trying to work out gravity for planets. What would the steps be in pseudo-code for this to happen?

Was it helpful?

Solution

Relevant characteristics of each object: location, speed and direction of travel (tracking this as x-speed and y-speed may be easier), mass. It may of course have other attributes such as orientation which don't affect this. Or even attributes which do, such as its own rocket thrust, but let's start with the simple case and it should be obvious how to expand upon it.

At each animation step, 

  For each object,
    Calculate the gravitational force of every other object, based on our mass,
      their mass, and direction from us to them. 
    Sum those forces together to get the total x and y forces on this object
    Using F=ma, determine the acceleration applied to this object by this force
      (how much its speed changes in the x and y directions).

  For each object
    Use its x and y speeds to update its location.

Lather. Rinse. Repeat.

The smaller the steps you can take per pass, the more accurate this simulation will be... but of course it will run more slowly. And note that the computational cost goes as N-squared.

Note the process of calculating the gravitational force involves a bit of trig to figure out how much of the force is applied on the X axis and how much on the Y axis. The original Space War game ran on a PDP-1 at MIT. That machine didn't have enough power to calculate the trig functions in realtime even for its simple 2-body system (planet and ship). So instead what they did was precalculate two 2D lookup tables, one for each of the axes, which let them simply lookup the gravitational force on the ship at any point in the playing field.

Also, as Space War pointed out, it may be massive overkill to try to account for all the gravitational forces. The effect of one planet on another in our solar system is pretty minimal compared to the sun's gravity unless you're looking at millennial time scales. The effect of ships on each other, or on planets, is also tiny. You can account for it all, but it may be much more efficient to use simpler modelling for everything but ship navigation -- and for that, to consider only the nearest planet/moon and maybe the sun.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top