这是我第一次制作 2D 游戏。代码使用 Java。
我有一个可以向僵尸发射冲击波的角色,这就是我处理冲击波和僵尸之间的碰撞检测的方式。
我收到以下行的 ArrayIndexOutOfBounds 异常:blastIter.remove();
这是为什么?
Iterator<Rectangle> blastIter = blasts.iterator();
Iterator<Zombie> zombieIter;
while(blastIter.hasNext()) {
Rectangle blast = blastIter.next();
blast.x += 200 * Gdx.graphics.getDeltaTime();
if(blast.x > window.length) blastIter.remove();
zombieIter = zombies.iterator();
while(zombieIter.hasNext()) {
Zombie zombie = zombieIter.next();
if(zombie.overlaps(blast)) {
zombie.removeHealth(5);
blastIter.remove();
if (zombie.isDead()) {
zombiesSlain++;
zombieIter.remove();
}
}
}
}
根据要求,这里是完整的堆栈跟踪:
线程“LWJGL 应用程序”中的异常 java.lang.ArrayIndexOutOfBoundsException: -1 在 com.badlogic.gdx.utils.Array.removeIndex(Array.java:231) 在 com.badlogic.gdx.utils.Array$ArrayIterator.remove(Array.java:540) 在 com.test.drop.Drop.render(Drop.java:128) 在 com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:208) 在 com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
最佳答案
在内部循环中使用 blastIter.remove();
是有问题的,因为您可能会多次尝试删除相同的爆炸。此外,您可能会在到达内循环之前移除爆炸,在这种情况下应该跳过内循环。
我建议添加一个标志,以防止 blast 被多次删除:
while(blastIter.hasNext()) {
Rectangle blast = blastIter.next();
blast.x += 200 * Gdx.graphics.getDeltaTime();
boolean removed = false;
if(blast.x + 16 > window.length) {
blastIter.remove();
removed = true;
}
zombieIter = zombies.iterator();
while(zombieIter.hasNext() && !removed) {
Zombie zombie = zombieIter.next();
if(zombie.overlaps(blast)) {
removed = true;
zombie.removeHealth(5);
blastIter.remove();
if (zombie.isDead()) {
zombiesSlain++;
zombieIter.remove();
}
}
}
}
关于java - 我收到 ArrayIndexOutOfBounds 异常,我不知道为什么。有人可以阐明一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786075/