Null Pointer Exception Error
in
Programming Questions
•
1 year ago
The purpose of this is to have bouncing balls that bounce off the walls and each other. Now when I try to get them to bounce off eachother I keep getting a NullPointerExeception Error.
int num = 9;
int numTarget = 9;
Target[] target = new Target[numTarget];
void setup() {
size(500, 500);
frameRate(30);
PFont font;
font = loadFont("AlBayan-48.vlw");
textFont(font);
Target t1 = new Target(150, 150, 5, 1, 1);
Target t2 = new Target(150, 300, 5, 1, 1);
Target t3 = new Target(150, 450, 5, 1, 1);
Target t4 = new Target(300, 150, 5, 1, 1);
Target t5 = new Target(300, 300, 5, 1, 1);
Target t6 = new Target(300, 450, 5, 1, 1);
Target t7 = new Target(450, 150, 5, 1, 1);
Target t8 = new Target(450, 300, 5, 1, 1);
Target t9 = new Target(450, 450, 5, 1, 1);
}
void draw() {
background(0);
for (int i = 1; i < numTarget; i++) {
target[i].update();//-----------------------------This is where the error message appears.
target[i].move();
target[i].collision();
target[i].display();
}
}
class Target {
float xpos;
float ypos;
float speed;
float xdir;
float ydir;
Target (float x, float y, float s, float d, float c) {
xpos = x;
ypos = y;
speed = s;
xdir = d;
ydir = c;
}
void move() {
xpos += speed * xdir;
ypos += speed * ydir;
}
void display() {
ellipse(xpos, ypos, 25, 25);
}
void collision() {
for (int i = 0; i < numTarget - 1; i++) {
Target t1 = target[i];
for (int j = i + 1; j < numTarget; j++) {
Target t2 = target[j];
float dx = t2.xpos - t1.xpos;
float dy = t2.ypos - t1.ypos;
float d = sqrt(sq(dx)+sq(dy));
if (d < 25) {
xdir = xdir * -1;
}
}
}
if (ypos < 12.5 || ypos > height - 12.5) {
ydir = ydir * -1;
}
if (xpos < 12.5 || xpos > width - 12.5) {
xdir = xdir * -1;
}
}
void update() {
if (mousePressed && mouseX < xpos + 12.5 && mouseX > xpos - 12.5 &&
mouseY < ypos + 12.5 && mouseY > ypos - 12.5) {
xpos = 1000;
ypos = 1000;
speed = 0;
xdir = 0;
ydir = 0;
num--;
}
if (num == 0) {
text("You Win!", 150, 150);
}
}
}
1