java - 在 PVector 集上处理草图崩溃

标签 java crash processing

我一直在处理游戏,我遇到了这个问题:我正在尝试制作一个星星飞过的背景,我有这样的类(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/

相关文章:

JavaFX:如何使底层节点可访问?

java - org.jdesktop.swingbinding.JTableBinding$BindingTableModel 无法转换为 javax.swing.table.DefaultTableModel

ios - iPhone在基础结构代码上崩溃

C++ - Windows 上有类似 addr2line 的命令吗

javascript - P5 - 处理。无法同时运行和渲染多个草图

java - 我可以在spring服务层使用静态变量吗?

java - 当您需要存储(非常)大的数字时该怎么办?

C# : "A first chance exception of type ' System. InvalidOperationException'”

java - 旋转变换在处理循环时不起作用

java - 将 delayMicroseconds 函数添加到标准 firmata 以运行带处理的 Arduino