int96:NullPointerException

So here is the basic code… for the life of me I can’t see whats wrong.

sketch

Particle p;
Particle[] particles = new Particle[1];

void setup() {
  size(200, 200);
  particles[0] = new Particle();
}

void draw() {
  background(255);
  p.update();
  p.show();
}

class

class Particle {
  PVector pos;
  PVector vel;
  PVector acc;

  Particle() {
    pos = new PVector(0, 0);
    vel = new PVector(0, 0);
    acc = new PVector(0, 0);
  }

  void applyForce(PVector force) {
    acc.add(force);
  }

  void update() {
    pos.add(acc);
    pos.add(vel);
    acc.mult(0);
  }

  void show() {
    stroke(0);
    point(pos.x, pos.y);
  }
}

Particle p was never initialized so you can leave it out; that’s what has the null pointer and is causing the error. Then use a draw() that looks like this to draw array elements:

void draw() {
  background(255);
  for(int i = 0; i < particles.length; i++){
    particles[i].update();
    particles[i].show();
  }
}

You only set up the array for one particle, so if you look closely you’ll see the lone point at 0,0.

Welcome to the forum.

1 Like

face palm
Thank you!! I couldn’t see it!!
Thanks for the welcome.

Another way of doing it while using p is

for (Particle p : particles){
   p.update();
   p.show();
}
2 Likes

Ahhh thanks I’ll have to check that out.