T. Shaw T. Shaw - 3 months ago 14
Java Question

Processing sketch crashes on PVector set

I've been working on a game in Processing and I came upon this problem: I'm trying to make a background with stars flying past and I have this class:

public class Star {
PVector position;
float speed;

void draw() {
fill(255);
ellipse(position.x, position.y, speed, speed);

position.x -= speed;
}

public Star() {
speed = random(5);
position.set(width+speed,random(height));
}
}


I have an ArrayList for Stars called stars:

ArrayList<Star> stars = new ArrayList<Star>();


I call the constructor in a function drawBg():

if(random(12) < 1) {
stars.add(new Star());
}


But when drawBg is called and it creates a new Star(), the sketch crashes and it points to:

position.set(width+speed,random(height));


The IDE says "Could not run the sketch", and the console says:


Could not run the sketch (Target VM failed to initialize). For more
information, read revisions.txt and Help ? Troubleshooting.


Please help! Thank you!

Answer

By default, your position variable is null, meaning it doesn't point to an instance of PVector yet.

You never initialize that variable (using the new keyword to create a new instance of PVector), so it's still null when you call position.set() in the Star constructor. That causes an error, since you can't call a function on a null variable.

To fix this, just use the new keyword to create a new instance of PVector:

public Star() {
    speed = random(5);
    position = new PVector(width+speed,random(height));
}
Comments