My code for gravity is quite different. I never got round to doing a multiple gravities applet but this thread inspired me to try.
The code I picked up a while back dealt with particles drifting to one point - the mouse. I cobbled an
applet together and thought no more of it. (For the orbit I cheated by giving the particles centrifugal motion.)
Below I've reasoned that each planet probably percieves an average of the sum of gravities, and moves towards the gravitational average of the universe.
Code:
Orbiter [] planet;
void setup(){
size(400,350);
planet = new Orbiter[200];
for(int i = 0; i < planet.length; i++){
planet[i] = new Orbiter(random(width), random(height), random(2, 6));
}
ellipseMode(CENTER);
noStroke();
smooth();
}
void draw(){
background(0);
for(int i = 0; i < planet.length - 1; i++){
planet[i].grav(planet);
planet[i].draw();
planet[i].keepOnScreen();
}
}
class Orbiter{
float x, y, xVel, yVel, mass;
Orbiter(float x, float y, float mass){
this.x = x;
this.y = y;
this.mass = mass;
this.xVel = 0.0;
this.yVel = 0.0;
}
void grav(Orbiter [] other){
float distance = 0.0;
for(int i = 0; i < other.length; i++){
distance += dist(other[i].x, other[i].y, x, y);
}
distance /= other.length;
if (distance < 15){
distance = 15;
}
float grav = 0.0;
for(int i = 0; i < other.length; i++){
grav += (mass * other[i].mass) / sq(distance) * 5;
}
grav /= other.length;
float distX = 0.0;
for(int i = 0; i < other.length; i++){
distX += other[i].x - x;
}
float xGrav = 0.0;
for(int i = 0; i < other.length; i++){
xGrav += grav * (distX/distance);
}
xGrav /= other.length;
float xAccel = xGrav / mass;
xVel += xAccel;
x += xVel;
float distY = 0.0;
for(int i = 0; i < other.length; i++){
distY += other[i].y - y;
}
float yGrav = 0.0;
for(int i = 0; i < other.length; i++){
yGrav += grav * (distY/distance);
}
yGrav /= other.length;
float yAccel = yGrav / mass;
yVel += yAccel;
y += yVel;
}
void keepOnScreen(){
if(x - mass > width) x = 0 + mass;
if(y - mass > height) y = 0 + mass;
if(x + mass < 0) x = width - mass;
if(y + mass < 0) y = height - mass;
}
void draw(){
ellipse(x, y, mass*2, mass*2);
}
}
I tried sticking a central sun in but the particles didn't care. I don't think my code is correct. I think the planets should be reacting to each other in some way - rather than some imaginary average mass.