我上周开始开发《太空飞船与彗星》风格的游戏,现在我停下来了。
游戏的目的是在彗星通过您的飞船之前对其进行射击。您通过向它们射击使彗星爆炸。简单的想法!
但是,有时我在玩游戏时出现“ IndexOutOfBounds”错误。 它几乎总是出现在我没有开火一段时间(我的镜头ArrayList的大小为0),然后当我开火并碰撞时崩溃的原因。
所以我的代码中存在某种错误,但我确实看不到它。现在,我希望你们中的一个可以理解为什么会这样,并使我免于进一步的“ IndexOutOfBounds”错误! :)
这里是失败的代码部分,包括我用来移动彗星和镜头的功能:
游戏类别
if(!Game.player.getShots().isEmpty() && !comet.getComets().isEmpty()) { //Om de är tomma så ignorera
for(int x = 0; x < Game.player.getShots().size(); x++) { //Shots X
if(!comet.getComets().isEmpty() && !comet.getComets().isEmpty()) {
for(int y = 0; y < comet.getComets().size(); y++) { //Comets Y
if(comet.getComets().get(y).intersects(Game.player.getShots().get(x)) && !comet.getComets().isEmpty() && !Game.player.getShots().isEmpty()) {
//the for loop above is the line that won't compile sometimes
comet.getComets().remove(y);
Game.player.getShots().remove(x);
score++;
}
}
}
}
}
//Comet spawn timer
comet.addComets();
//Move the comets and shots!
Game.player.moveShots();
comet.moveComets();
repaint();
COMET CLASS
public ArrayList<Rectangle> getComets() {
return comets;
}
public void moveComets() {
if(!comets.isEmpty()) {
for(int x = 0; x < comets.size(); x++) {
comets.get(x).x -= cometSpeed;
}
}
}
PLAYER CLASS(此班级是射击)
public void fire() {
shots.add(new Rectangle(x + player.width, y + 23, shotWidth,shotHeight));
}
public ArrayList<Rectangle> getShots() {
return shots;
}
public void moveShots() {
if(!shots.isEmpty()) {
for(int x = 0; x < shots.size(); x++) {
shots.get(x).x += fireSpeed;
}
}
}
请记住,彗星和镜头都是“ ArrayList超出了对象的矩形”
我将在下面提供错误的屏幕截图和游戏图片!
错误代码在上面的代码中标记,if语句应阻止它崩溃(我认为)。
谢谢!感谢所有帮助! :)
尝试在此处调整if(!comet.getComets().isEmpty() && !comet.getComets().isEmpty())
。您正在两次检查彗星阵列。
让我知道它是否有效。
我不知道您为什么要双重验证同一条件
if(!comet.getComets()。isEmpty()&&!comet.getComets()。isEmpty())] >>
与if(comet.getComets()。isEmpty())并非完全相同]
您应该在if语句中更改顺序,以免评估其中一部分。您应该将条件更改为:
因此,它不能解决崩溃问题吗?我可以看到完整的错误堆栈吗?