2015-06-09 38 views
0

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

这就是我所做的:检测

//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); 
     } 
    } 
} 

触摸输入,但我不知道如何删除它们。
当我触摸它们时,结果是错误的。

+0

什么错误? ConcurrentModification?如果你有错误,最好包含堆栈跟踪。 – Gosu

+1

你在哪里声明'enemyIterator'?这是行不通的,因为无论'enemyIterator'引用什么,它都不是你的'draw'方法中使用的迭代器,因为你从来没有得到它的引用。此外,在测试是否触摸之前,您需要使用相机(未投影)将触摸坐标转换为世界坐标。 – Tenfour04

+0

是的,并发修改错误。迭代器可以通过所有方法访问。触摸检测的工作原理是因为我首先将它设置为在任何时候触及精灵并且它始终工作时打印出某些东西。 –

回答

0

您无法重复使用迭代器,因此您的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