我一直在处理游戏,我遇到了这个问题:我正在尝试制作一个星星飞过的背景,我有这样的类(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));
}
}
我有一个名为 stars 的 Stars ArrayList:
ArrayList<Star> stars = new ArrayList<Star>();
我在函数drawBg()中调用构造函数:
if(random(12) < 1) {
stars.add(new Star());
}
但是当调用drawBg并创建一个新的Star()时,草图崩溃并指向:
position.set(width+speed,random(height));
IDE 显示“无法运行草图”,控制台显示:
Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help ? Troubleshooting.
请帮忙!谢谢!
最佳答案
默认情况下,您的 position
变量为 null
,这意味着它尚未指向 PVector
实例。
您从未初始化该变量(使用new
关键字创建PVector
的新实例),因此它仍然null
当您在 Star
构造函数中调用 position.set()
时。这会导致错误,因为您无法对 null
变量调用函数。
要解决此问题,只需使用 new
关键字创建 PVector
的新实例即可:
public Star() {
speed = random(5);
position = new PVector(width+speed,random(height));
}
关于java - 在 PVector 集上处理草图崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086722/