Code:
ax = -dx * G * Mb / r^3
ay = -dy * G * Mb / r^3
We both made a mistake here.
I swapped Ma and Mb (already fixed that in my post)
You incorrectly placed minus signs in front of dx and dy
To give you an example for the minus signs:
suppose A is right of B (xa > xb, ya == yb).
Then, in my convention, dx > 0 and dy = 0.
Gravity is an attracting force, so B will accelerate to the right.
So, ax has to become positive.
G, Ma and r are all positive, so G*Ma/r^3 is positive.
dx is also positive, so everything is OK
without the minus sign.
Lastly, but it's getting a little advanced, you can play with the exponent of the force equation. if
F = -G m M / r^2, you can state generally that
a = -k r^n, where k is any constant you like, and play with the exponent. For instance, n = -2 is like gravity. With n = 1 the bodies will behave as if they were linked by springs.
You are a mathematician, aren't you?
-----Post Added-----
I don't think this could be much more complicated than your way.
Not much more complicated, but it uses trigonometry, while I use vector calculus. I prefer (cartesian) vector calculus, because it doesn't have as many nasty singularities (e.g. the direction of a line of length 0) and things like multiple representations of the same position (e.g. 0 degree == 360 degree). Further, if you want to do number crunching, it's usually faster. Finally, for me it's more straightforward to understand, but maybe that's different for other people.
I also use two loops for a slightly more accurate numerical integration. When I leave that away, and also use some other of your simplifications, for comparison with your code, my code would look like this:
Code:
for(int i = 0; i < objects; i++) {
for(int j = 0; j < objects; j++) {
if(i == j) continue;
dx = xpos[j] - xpos[i];
dy = ypos[j] - ypos[i];
distance = sqrt(dx*dx + dy*dy);
xvel[i] += dx * 100 / Math.pow(distance, 3);
yvel[i] += dy * 100 / Math.pow(distance, 3);
}
}
xpos[i] += xvel[i];
ypos[i] += yvel[i];
}
(Why do you have -= instead of += on the velocity-to-position integration?)