从数组中删除内容但游戏崩溃

时间:2014-10-27 14:48:52

标签: java arrays libgdx

我有和数组,我在平铺地图上创建了几把剑,当我踩到它们时,它们需要被删除但是当我踩到它们时游戏会发生冲突。

at java.util.ArrayList $ Itr.checkForComodification(Unknown Source) at java.util.ArrayList $ Itr.next(Unknown Source)

我的代码:

我猜循环正在寻找对象,即使它被删除了吗?

private List<Sword> swords = new ArrayList<Sword>();

我创造了一次:

public GameRender(GameWorld world, int gameHeight) {
    for (int i = 0; i<100 ; i++ ) {
        swords.add(new Sword());
        }

当我踩到它时:

for (Sword sword : swords) { 
        if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
        && playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
                sword.pickMe();   
                swords.remove(sword);
        }
    }

render()中还有其他循环:

for (Sword sword : swords) {
        sword.createMe();
    }

我认为你不需要看Sword课程。如果你这样做我会把它放在这里。我如何解决它,所以我没有得到错误?

1 个答案:

答案 0 :(得分:2)

for (Sword sword : swords) { 
        if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
        && playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
                sword.pickMe();   
                swords.remove(sword); //this line throws ConcurrentModificationException
        }
}

由于增强型for循环的工作原理,您需要使用Iterator<Sword>将其删除:

Iterator<Sword> iterator = swords.iterator();
while(iterator.hasNext())
{
    Sword sword = iterator.next();
        if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
        && playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
                sword.pickMe();   
                iterator.remove();
        }
}

或以下内容:

  for (int i = 0; i < swords.size(); i++) { 
        Sword sword = swords.get(i);
        if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
        && playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
                sword.pickMe();   
                swords.remove(i--);
        }
  }