Reputation: 93
Im trying to make a basic frogger game. All I am trying to do it make a class for my frog image, and then I want it have it shown under void draw();
Except I keep getting NullPointException, can anyone help me figure out why?
This is the code I've been playing with to try and figure out the issue.
PImage img; // frog image
Frog froggy;
Car[] c1;
class Car {
float xpos;
int ypos;
int sizel;
int sizew;
float yspeed;
color c;
Car(){
xpos = 0;
ypos = (int)random(120,480);
sizel = (int)random(20,30);
sizew = 15;
yspeed = (float)random(1,3);
c= color(random(255), random(255), random(255));
}
void carShape() {
rectMode(CENTER);
fill(c);
rect(xpos,ypos,sizel,sizew);
fill(0);
rect(xpos-5, ypos-8, 8,5);
rect(xpos+5, ypos-8, 8,5);
rect(xpos-5, ypos+8, 8,5);
rect(xpos+5, ypos+8, 8,5);
}
void moveCar () {
xpos = xpos + yspeed;
if (xpos > width) {
xpos = 0;
ypos = (int)random(120,480);
}
}
}
class Frog {
int frogx;
int frogy;
Frog(){
frogx = width/2-20;
frogy = 527;
}
void drawFrog() {
image(img,frogx,frogy);
}
}
void setup() {
size(800,600);
img = loadImage("frog.png");
c1 = new Car[20];
for(int i=0; i<20; i++) {
c1[i] = new Car();
}
}
void draw() {
background(100);
froggy.drawFrog();
for(int i=0; i<20; i++) {
c1[i].carShape();
c1[i].moveCar();
}
}
Heres the error
Exception in thread "Animation Thread" java.lang.NullPointerException
at snowflakecarexample.draw(snowflakecarexample.java:97)
at processing.core.PApplet.handleDraw(PApplet.java:2120)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:197)
at processing.core.PApplet.run(PApplet.java:1998)
at java.lang.Thread.run(Thread.java:680)
Upvotes: 1
Views: 272
Reputation: 46428
you din't initialize
Frog
object.
try
Frog froggy = new Frog();
froggy.drawfrog();
Upvotes: 3
Reputation: 351
In the moveCar()
function you are checking if (xpos > width)
, but I don't see width declared anywhere. Unless it is declared and not in the snippet you have posted, this could be the issue.
You also use width in the Frog()
function.
Upvotes: 0
Reputation: 1290
Whatever froggy should be, it must be initialized:
Frog froggy;
... (Froggy is null)
froggy.drawFrog();
perhaps you want to call a constructor somewhere? Like:
Frog froggy = new Frog();
Upvotes: 2