Unknown cause for a NullPointerException
in
Programming Questions
•
1 year ago
I'm making a game, and I'm trying to have a game over sequence run when the controlled character (player2) comes in contact with the enemy (enemy1).
I have this if statement:
if(player2.xpos == enemy1.x && player2.ypos == enemy1.y){
gameState="gameOver";
}
The player2 class (relevant variables in red):
class player2 {
PImage[] sprites;
String current_pose;
float xpos,ypos;
void init(String prefix) {
sprites=new PImage[16];
for(int i=0;i<=15;i++) {
sprites[i]=loadImage(prefix+i+".png");
}
//initiate values
current_pose="stand";
xpos
=width/5;
ypos
=height-45;
}
void update(float x, float y) {
if (current_pose.equals("stand")) {
pushMatrix();
translate(x, y);
image(sprites[0], -sprites[0].width/2, -sprites[0].height/2);
popMatrix();
}
if (current_pose.equals("walk")) {
if(movedown) {
image(sprites[8],x-sprites[8].width/2,y-sprites[8].height/2);
}
if(moveleft) {
image(sprites[4],x-sprites[4].width/2,y-sprites[4].height/2);
}
if(moveright) {
image(sprites[12],x-sprites[12].width/2,y-sprites[12].height/2);
}
if(moveup) {
image(sprites[2],x-sprites[2].width/2,y-sprites[2].height/2);
}
}
}
}
The enemy1 class:
class enemy1 {
Float x,y;
enemy1() {
}
void init() {
x
=1.0*width+100;
y
=random(90,height-90);
}
void update() {
x
-=2;
image(jellyfish,
x
-jellyfish.width/3,
y
-jellyfish.height/3);
}
}
The if statement gets highlighted when I run the sketch with "NullPointerException", and the following message:
processing.app.debug.RunnerException: NullPointerException
at processing.app.Sketch.placeException(Sketch.java:1543)
at processing.app.debug.Runner.findException(Runner.java:583)
at processing.app.debug.Runner.reportException(Runner.java:558)
at processing.app.debug.Runner.exception(Runner.java:498)
at processing.app.debug.EventThread.exceptionEvent(EventThread.java:367)
at processing.app.debug.EventThread.handleEvent(EventThread.java:255)
at processing.app.debug.EventThread.run(EventThread.java:89)
Exception in thread "Animation Thread" java.lang.NullPointerException
at midterm.draw(midterm.java:278)
at processing.core.PApplet.handleDraw(PApplet.java:1606)
at processing.core.PApplet.run(PApplet.java:1503)
at java.lang.Thread.run(Thread.java:680)
Why? What do I have to do for this to work? In the player2 class, I'm using .png sprites to animate the player's movement (up down left right). In the enemy1 class, 'jellyfish' is an animated gif being called with the gifAnimation library, and they're also being called in an arrayList. Any ideas on the source of the issue?
I'd post the whole sketch but it's all a huge mess and I don't want to confuse anyone who might be able to spot the issue without it. Any tips at all would be greatly appreciated!
1