2015-06-09 40 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