【问题标题】:How can I remove a sprite from an arrayList of sprites and remove it off the screen when a collision happens with the sprite? Java/Libgdx当精灵发生碰撞时,如何从精灵数组列表中删除精灵并将其从屏幕上删除? Java/Libgdx
【发布时间】:2017-11-21 03:16:00
【问题描述】:

在我的游戏中,我希望能够收集硬币。我有一个该硬币精灵的数组列表,这样我就可以分别绘制多个分开的硬币。这些硬币也随着背景移动(模拟汽车驾驶),我想要它,所以当硬币撞到汽车时,它会消失并被收集。 感谢您的帮助。

【问题讨论】:

  • 使用ArrayList函数remove(index)删除指定位置的精灵。

标签: java libgdx collision


【解决方案1】:

您可以使用SpritegetBoundingRectangle() 方法并检查是否存在与其他矩形的碰撞,如果是,您可以从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 类。

【讨论】:

  • 你最好使用 Iterator 来防止将来出现 ConcurrentModificationException,还有 Array 在 libgdx 中实现,它是 arraylist 的首选集合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多