在我的游戏中,我希望能够收集硬币。我有一枚硬币的精灵阵列,这样我就可以分别画出多个硬币。这些硬币也随着背景移动(模仿汽车驾驶),我想要它,所以当硬币撞到汽车时,它会消失并被收集起来。 谢谢你的帮助。如何从精灵的arrayList中移除精灵并在精灵发生碰撞时将其从精灵屏幕中移除? Java/Libgdx
2
A
回答
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
相关问题
- 1. 如何让精灵从精灵表变成另一个精灵?
- 2. 从屏幕cocos2d iphone中删除精灵?
- 3. 如何检测精灵表的精灵帧的碰撞
- 4. 与UIImageView碰撞的精灵
- 5. 从屏幕上删除精灵
- 6. 如何删除与其他精灵相交的精灵cocos2d-android
- 7. 如何删除精灵并再次使用相同的精灵
- 8. 当精灵离开屏幕时,将精灵移动到另一侧Pygame
- 9. 从精灵表
- 10. 移相器 - 用另一个精灵移动精灵
- 11. Swift如何移动精灵?
- 12. Phaser P2碰撞杀死碰撞精灵
- 13. 定时移动精灵
- 14. 如何从精灵网格中提取单个精灵?
- 15. 从其他计算机移动精灵
- 16. Python pygame - 删除屏幕外精灵
- 17. 移动精灵的方向
- 18. Phaser - 如何检查在两个其他精灵之间移动的精灵?
- 19. 自动移动一个精灵来捕捉另一个精灵
- 20. 精灵在LESSC
- 21. 移动精灵直线
- 22. 获取精灵节偏移
- 23. 沿路径移动精灵
- 24. 如何让精灵在XNA中跟随另一个精灵?
- 25. 不能让我的精灵碰撞?
- 26. 查找两个精灵的碰撞点
- 27. AndEngine合并精灵
- 28. Cocos2D简单碰撞检测一个精灵,另一个精灵的子女
- 29. Cocos2d:删除精灵时出现黑屏
- 30. Unity3D中的另一个精灵如何向上精灵?
使用'ArrayList'函数'remove(index)'去除指定位置的精灵。 –