← back to the log
Entry № 05 / 09
ProcessingVisualisation
Gravity Simulator.
Filed under Processing · Visualisation
Status Logged
Index № 05 / 09
Author Nikolaos Pappas
Context
The main challenge of building a physics engine wasn't the physics — it was how to transpose simple Trigonometry within the world of a Java program.
Newton's Law of Universal Gravitation states F = G · (M·m / r²), where G is the gravitational constant, M and m are masses, and r the distance between objects.
Java doesn't ship with built-in vector support, so I replaced the net acceleration with its constituents on a chosen 2D plane — decomposing forces into x and y components with trig.
Going the other way — converting components back into magnitude and angle — meant working around the limited range of Java's atan(). Once that clicked, the rest fell into place.
Processing Sketch
//...
final GravitySimulator sim = new GravitySimulator();
final List<Trio<Float>> colours = new ArrayList<>();
@Override
public void settings() {
size(900, 600);
}
@Override
public void setup() {
super.setup();
background(20, 30, 30);
addParticle(new Particle(100000, -100, 10));
//... Adding more particles.
}
@Override
public void draw() {
background(20, 30, 30);
ellipseMode(CENTER);
List<Particle> particles = sim.getParticles();
stroke(200);
for (int i = 0; i < particles.size(); i++) {
Trio<Float> colour = colours.get(i);
fill(colour._1, colour._2, colour._3);
Particle p = particles.get(i);
float x = width * .5f + (float) p.x;
float y = height * .5f + (float) p.y;
circle(x, y, max((float) p.mass * 0.000001f, 2.0f));
}
delay(40);
}