2017-06-19 86 views
2

在我的游戏中,我希望能够收集硬币。我有一枚硬币的精灵阵列,这样我就可以分别画出多个硬币。这些硬币也随着背景移动(模仿汽车驾驶),我想要它,所以当硬币撞到汽车时,它会消失并被收集起来。 谢谢你的帮助。如何从精灵的arrayList中移除精灵并在精灵发生碰撞时将其从精灵屏幕中移除? Java/Libgdx

+0

使用'ArrayList'函数'remove(index)'去除指定位置的精灵。 –

回答

1

您可以使用getBoundingRectangle()方法Sprite并检查是否存在与其他矩形的碰撞,如果是,您可以从coinList中移除该硬币。

ArrayList<Sprite> coinList; 
Sprite car; 

@Override 
public void create() { 

    coinList=new ArrayList<>(); 
    car=new Sprite(); 
    coinList.add(new Sprite()); 
} 

@Override 
public void render() { 

    //Gdx.gl.... 

    spriteBatch.begin(); 
    for (Sprite coin:coinList) 
     coin.draw(spriteBatch); 
    spriteBatch.end(); 

    for(Sprite coin:coinList) 
     if(car.getBoundingRectangle().overlaps(coin.getBoundingRectangle())) { 
      coinList.remove(coin); 
      break; 
     } 
} 

编辑

您可以使用Iterator防止ConcurrentModificationException

for (Iterator<Sprite> iterator = coinList.iterator(); iterator.hasNext();) { 
    Sprite coin = iterator.next(); 
    if (car.getBoundingRectangle().overlaps(coin.getBoundingRectangle())) { 
     // Remove the current element from the iterator and the list. 
     iterator.remove(); 
    } 
} 

可以使用Array代替ArrayList,有一堆classes内libGDX被优化,以避免垃圾收集尽可能也哈有很多好处。

您应该随时尝试使用libGDX类。

+0

您最好使用迭代器来防止将来出现ConcurrentModificationException异常,还有在libgdx中实现的Array ,这是ArrayList上的首选集合。 – eldo