【发布时间】:2017-11-21 03:16:00
【问题描述】:
在我的游戏中,我希望能够收集硬币。我有一个该硬币精灵的数组列表,这样我就可以分别绘制多个分开的硬币。这些硬币也随着背景移动(模拟汽车驾驶),我想要它,所以当硬币撞到汽车时,它会消失并被收集。 感谢您的帮助。
【问题讨论】:
-
使用
ArrayList函数remove(index)删除指定位置的精灵。
在我的游戏中,我希望能够收集硬币。我有一个该硬币精灵的数组列表,这样我就可以分别绘制多个分开的硬币。这些硬币也随着背景移动(模拟汽车驾驶),我想要它,所以当硬币撞到汽车时,它会消失并被收集。 感谢您的帮助。
【问题讨论】:
ArrayList函数remove(index)删除指定位置的精灵。
您可以使用Sprite 的getBoundingRectangle() 方法并检查是否存在与其他矩形的碰撞,如果是,您可以从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,libGDX 内部有一堆classes 进行了优化,以尽可能避免垃圾收集也有很多好处。
您应该始终尽可能使用 libGDX 类。
【讨论】: