You need to create all the particles
before you create the attractions. In your code you are trying to calculate the attractions between none existent particles.
Also in the code where you create attractions you have
Code: if(j != i) {
f[i][j] = physics.makeAttraction(p[i], p[j], k, 1);
}
else {
f[i][j] = physics.makeAttraction(p[i], p[j], 0.0, 0.0);
}
this is obviously to prevent attractions between a particle and itself but this is what happens in the else part. Making a few changes we have the following code which solves the null reference exception problem.
Code:import traer.physics.*;
int n = 10, k = -5;
ParticleSystem physics;
Particle[] p = new Particle[n], a = new Particle[n];
Spring[] s = new Spring[n];
Attraction[][] f = new Attraction[n][n];
void setup() {
size(400,400);
smooth();
fill(255, 200);
stroke(255, 200);
ellipseMode( CENTER );
physics = new ParticleSystem( 1, 0.05 );
for(int i = 0; i < n; i++) {
p[i] = physics.makeParticle( 1.0, width/2, height/2, 0 );
a[i] = physics.makeParticle( 1.0, random(0,width), height/2, 0 );
a[i].makeFixed();
s[i] = physics.makeSpring( p[i], a[i], 0.5, 0.1, 75 ); // Connects anchor to particle
}
// If this is commented out then the pde runs---Start
// Create an attraction between all free particles
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(j != i) {
f[i][j] = physics.makeAttraction(p[i], p[j], k, 1);
}
}
}
// If this is commented out then the pde runs---End
}
void draw() {
physics.tick();
//background( 51, 181, 74 ); // Green
background( 0, 182, 235 ); // Cyan
for(int i = 0; i < n; i++) {
line( p[i].position().x(), p[i].position().y(), a[i].position().x(), a[i].position().y() );
ellipse( a[i].position().x(), a[i].position().y(), 5, 5 );
ellipse( p[i].position().x(), p[i].position().y(), 20, 20 );
}
}