【发布时间】:2022-01-25 11:54:13
【问题描述】:
一些上下文,我正在开发一个小行星游戏
所以,我的 Asteroid 是一个多边形(Java 内置对象),而子弹只是一个点。
当我试图检测小行星和子弹之间的碰撞时,我使用Polygon.contains(x,y) 和子弹坐标。
但由于某种原因,我在使用此方法时得到 NullPointerException,但有时我只会得到异常 99% 的时间一切正常,然后我得到这个异常。
当我射击子弹时,我得到了一个异常,如果抛出异常,子弹将停止(子弹是一个线程,所以线程死了)。
以下是相关代码:
for (int i = 0; i <= Math.ceil(l); i++) {
try {
t = i / (l - extension);
y = (int) ((t * (cursorPos.y - initY)) + initY);
x = (int) ((t * (cursorPos.x - initX)) + initX);
if (!PlayerPanel.meteorList.isEmpty()) {
synchronized (PlayerPanel.meteorList) {
for (int j = 0; j < PlayerPanel.meteorList.size(); j++) {
if (PlayerPanel.meteorList.get(j).shapes[PlayerPanel.meteorList.get(j).selectedMeteor].contains(x, y)) { // Line 39
PlayerPanel.meteorList.get(j).shapes[PlayerPanel.meteorList.get(j).selectedMeteor].invalidate();
PlayerPanel.playerScore+=10;
PlayerPanel.scoreLabel.setText("Score: " + PlayerPanel.playerScore);
synchronized (PlayerPanel.bulletList) {
PlayerPanel.bulletList.remove(this);
}
PlayerPanel.meteorList.remove(PlayerPanel.meteorList.get(j));
return;
}
}
}
}
TimeUnit.NANOSECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
小行星被存储在一个列表中,子弹也是如此
例外:
Exception in thread "Thread-2" java.lang.NullPointerException
at java.desktop/java.awt.Polygon.getBoundingBox(Polygon.java:335)
at java.desktop/java.awt.Polygon.contains(Polygon.java:398)
at java.desktop/java.awt.Polygon.contains(Polygon.java:364)
at Bullet.run(Bullet.java:39)
【问题讨论】:
标签: java list thread-safety polygon synchronized