2017-06-19 67 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