我知道这可能已经被问过很多次了,但是我有一个问题,我找不到特别针对我的问题的解决方案。
问题如下:
我有两个火箭和射弹的数组列表,并检查它们之间的碰撞。当它们碰撞时,它们都会被移除。问题是,当arraylist中唯一的火箭被击中时,就会发生异常,我不知道如何阻止它发生。
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at adam.miszczak.defendthebase.level.Level.collision(Level.java:158)
at adam.miszczak.defendthebase.level.Level.tick(Level.java:144)
at adam.miszczak.defendthebase.Game.tick(Game.java:124)
at adam.miszczak.defendthebase.Game.run(Game.java:104)
at java.lang.Thread.run(Unknown Source)
碰撞方法 + 数组列表:
public static ArrayList<Projectile> projectiles = new ArrayList<Projectile>();
private static ArrayList<Rocket> rockets = new ArrayList<Rocket>();
private void collision(){
for(int i = 0; i < rockets.size(); i++){
for(int j = 0; j < projectiles.size(); j++){
try{
if(rockets.get(i).bounds().intersects(projectiles.get(j).bounds())){
projectiles.remove(j);
rockets.get(i).die();
stats.addScore(rockets.get(i));
Particle p = new Particle(20, 20, 20, 50);
particles.add(p);
}
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
}
删除和添加方法:
private void remove(ArrayList<Projectile> projectiles, ArrayList<Rocket> rockets){
for(int i = 0; i < rockets.size(); i++){
if(rockets.get(i).getVisible()){ rockets.remove(i); rocketsOnScreen--; }
}
for(int i = 0; i < projectiles.size(); i++){
if(projectiles.get(i).isRemoved()){ projectiles.remove(i);}
}
for(int i = 0; i < planes.size(); i++){
if(planes.get(i).isRemoved()){ planes.remove(i); planesOnLevel--;}
}
}
private void spawnRocket(int rocketType, int x, ArrayList<Rocket> rockets) {
switch (rocketType) {
case ROCKET_NORMAL:
rockets.add(new NormalRocket(x, -10, 80, 0, 2));
rocketsSpawned++;
rocketsOnScreen++;
break;
case ROCKET_FIRE:
if(difficulty > 1 && random.nextInt(100) > fireRocketSpawn){
rockets.add(new FireRocket(x, -10, 70, 0, 2));
rocketsSpawned++;
rocketsOnScreen++;
}else{
return;
}
break;
case ROCKET_ZIPPER:
if(difficulty > 2 && random.nextInt(100) > zipperRocketSpawn){
rockets.add(new ZipperRocket(x, -10, 40, 0, 4));
rocketsSpawned++;
rocketsOnScreen++;
}else{
return;
}
break;
case ROCKET_TANK:
if(difficulty > 3 && random.nextInt(100) > tankRocketSpawn){
rockets.add(new TankRocket(x, -10, 130, 0, 1));
rocketsSpawned++;
rocketsOnScreen++;
}else{
return;
}
break;
}
}
注意:rocket.die() 基本上只是移除火箭,就像 remove 方法一样。