Search code examples
javagravity

Java Simulate realistic gravity


How would I go about programming a gravity simulator? I am making a kind of 2d space-simulator and what I want is to have a planet (a center of gravity) to pull objects towards it. The object is a spaceship (basically just x and y-coordinates).


Solution

  • Check out Princeton's N-Body assignment. It describes what you want.

    However, in the interest of quick summaries, you can derive the equations from basic trigonometry and Newton's Law of Universal Gravitation:

    F = GMm/(r^2)
    

    where F = force between two objects, G = gravitational constant, M and m are the relevant masses, and r is the distance between them.

    A little mathemagic and you get the following results:

    F_x = F(x_2 - x_1)/r
    F_y = F(y_2 - y_1)/r
    

    where F_x is the gravitational force in the x direction (same for F_y, but in y direction), x_2 and y_2 is the position of one of your objects, x_1 and y_1 the position of the other, F is as defined above, and r is the distance between them.