您无法重复使用迭代器,因此您的enemyIterator
无效并会导致异常。
为避免需要这样做,请更改您的touchInput
方法以简单测试是否应删除该对象,而不是将其删除。另外请注意,您需要将屏幕坐标转换为世界坐标,因此您也必须使用相机。
private Vector3 TMPVEC = new Vector3();
public boolean touched(float x,float y,float w,float h) {
TMPVEC.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(TMPVEC);
return Gdx.input.justTouched() && TMPVEC.x > x && TMPVEC.x < x+w;
}
您只能在迭代的地方使用迭代器。所以,你必须获得在循环这样的本地参考:
public void draw(SpriteBatch batch) {
for (Iterator<Sprite> iterator = enemies.iterator(); iterator.hasNext();) {
Sprite drawEnemy = iterator.next();
drawEnemy.draw(batch);
drawEnemy.translateY(deltaTime * movement);
if (touched((drawEnemy.getX(),drawEnemy.getY(), drawEnemy.getWidth(),drawEnemy.getHeight())){
iterator.remove();
Pools.free(sprite);
}
}
}
然而,上面是那种浑浊的,因为你混合更新和绘制代码在一起,并在更新前绘制,并检查无需重复触摸。我想重做这一切是这样的:
private Vector3 TMPVEC = new Vector3();
public void update (Camera camera, float deltaTime) {
boolean checkTouch = Gdx.input.justTouched();
if (checkTouch) {
TMPVEC.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(TMPVEC);
} //This way we only unproject the point once for all sprites
for (Iterator<Sprite> iterator = enemies.iterator(); iterator.hasNext();) {
Sprite enemy = iterator.next();
enemy.translateY(deltaTime * movement);
if (checkTouch && touched(enemy, TMPVEC)){
iterator.remove();
Pools.free(sprite);
}
}
}
private void touched (Sprite sprite, Vector3 touchPoint){
return sprite.getX() <= touchPoint.x &&
sprite.getX() + sprite.getWidth() <= touchPoint.x;
}
public void draw (SpriteBatch batch){
for (Sprite sprite : enemies) sprite.draw(batch);
}
在这里,你会draw
从所属的类之前调用update
。
什么错误? ConcurrentModification?如果你有错误,最好包含堆栈跟踪。 – Gosu
你在哪里声明'enemyIterator'?这是行不通的,因为无论'enemyIterator'引用什么,它都不是你的'draw'方法中使用的迭代器,因为你从来没有得到它的引用。此外,在测试是否触摸之前,您需要使用相机(未投影)将触摸坐标转换为世界坐标。 – Tenfour04
是的,并发修改错误。迭代器可以通过所有方法访问。触摸检测的工作原理是因为我首先将它设置为在任何时候触及精灵并且它始终工作时打印出某些东西。 –