触摸时删除精灵

精灵每秒产生一次,当它被触摸时,它应被移除。

这就是我做的:

//Render the sprites and making them move: public void draw(SpriteBatch batch) { for(Sprite drawEnemy:enemies) { drawEnemy.draw(batch); drawEnemy.translateY(deltaTime * movement); touchInput(drawEnemy.getX(),drawEnemy.getY(), drawEnemy.getWidth(),drawEnemy.getHeight(),drawEnemy); } } //Detecting the touch input: public void touchInput(float x,float y,float w,float h,Sprite sprite){ float touchX=Gdx.input.getX(); float touchY=Gdx.input.getY(); if(Gdx.input.justTouched()){ if(touchX > x && touchX < x+w ){ enemyIterator.remove(); Pools.free(sprite); } } } 

检测到触摸输入,但我不确定如何删除它们。
触摸它们时结果是错误。

您不能重用迭代器,因此您的enemyIterator无效并将导致exception。

为避免需要这样做,请更改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 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 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); } 

在这里你可以在拥有类之前调用update