2012-02-19 96 views
3

我正在創建大量隨機在屏幕上彈跳的精靈。當感動時,我想把球從場景中移開。 (如果不止一個球佔據相同的空間,那麼此時也會被刪除)。使用Andengine安全刪除精靈

我意識到scene.detachChild必須在runOnUpdateThread運行,所以我的球精靈子類中,我detachChild觸摸通過重寫onAreaTouched:

 @Override 
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) 
    { 
     ((BaseGameActivity) thisAct).runOnUpdateThread(new Runnable() { 
      @Override 
      public void run() { 
       /* Now it is save to remove the entity! */ 


        //scene.unregisterTouchArea(Ball.this); 
        scene.detachChild(Ball.this); 

      } 
     }); 
     return false; 
    } 

我在主要活動傳遞給構造的球精靈,然後從主活動場景中移除球。

如果我取消註釋scene.unregisterTouchArea(Ball.this)這一行,以停止對接觸進行操作的精靈(這不會影響移除,但認爲最好是停止正在處理的接觸),我會收到我認爲indexOutOfBoundsException與不從runOnUpdateThread中分離精靈有關。

**java.lang.IndexOutOfBoundsException: Invalid index 90, size is 90 
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257) 
at java.util.ArrayList.get(ArrayList.java:311) 
at org.anddev.andengine.entity.scene.Scene.onSceneTouchEvent(Scene.java:320)** 

兩個問題:

  1. 我是正確處理去除球子類中的精靈,使用覆蓋onAreaTouched,或者我應該以某種方式採取去除回主活動(首先需要一個子類)?

  2. 任何想法,爲什麼我得到IndexOutOfBoundsException,如果我包含unregisterTouchArea?

感謝您的任何幫助。

回答

3

千萬別在TouchListener中刪除。你應該堅持一個IUpdateHandler

1.)不需要繼承子類,可以在任何可以訪問場景的地方執行刪除操作。

2.)發生IndexOutOfBoundException是因爲您在TouchListener中執行刪除操作。在刪除精靈時,可能有些方法會將新東西添加到場景中。將刪除放入UpdateHandler可解決此問題。

+0

嗨,感謝您的迴應。我意識到我應該在onLoadScene中使用registerOnTouchArea,這樣我就可以完全脫離Ball類。 – Chris 2012-02-22 13:00:41

0
/* 
     * Removing entities can only be done safely on the UpdateThread. Doing 
     * it while updating/drawing can cause an exception with a suddenly 
     * missing entity. Alternatively, there is a possibility to run the 
     * TouchEvents on the UpdateThread by default, by doing: 
     * engineOptions.getTouchOptions().setRunOnUpdateThread(true); when 
     * creating the Engine in onLoadEngine(); 
     */ 
     MainActivity.this.runOnUpdateThread(new Runnable() { 
      @Override 
      public void run() { 
       /* Now it is safe to remove the entity! */ 
       mScene.detachChild(face); 
      } 
     });