2011-08-22 82 views
3

我有一個方法makeExplosion如何讓AnimatedSprite播放一次然後自行移除?

private void makeExplosion(float x, float y){ 
    final AnimatedSprite explosion = new AnimatedSprite(x, y, BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mExplosionBitmapTextureAtlas, this, "explosion.png", 0, 0, 4, 2)); 
    explosion.animate(50); 
    mScene.attachChild(explosion); 
    explosion.registerUpdateHandler(new IUpdateHandler(){ 

     @Override 
     public void onUpdate(float pSecondsElapsed) { 
      if(explosion.getCurrentTileIndex() == 7){ 
       mScene.detachChild(explosion); 
      } 
     } 

     @Override 
     public void reset() { 

     }}); 
} 

..這是行不通的。我得到以下錯誤:

FATAL EXCEPTION: UpdateThread 
java.lang.IndexOutOfBoundsException: Invalid index 19, size is 19 
    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257) 
    at java.util.ArrayList.get(ArrayList.java:311) 
    at org.anddev.andengine.entity.Entity.onManagedUpdate(Entity.java:1024) 
    at org.anddev.andengine.entity.scene.Scene.onManagedUpdate(Scene.java:250) 
    at org.anddev.andengine.entity.Entity.onUpdate(Entity.java:882) 
    at org.anddev.andengine.engine.Engine.onUpdateScene(Engine.java:488) 
    at org.anddev.andengine.engine.Engine.onUpdate(Engine.java:483) 
    at org.anddev.andengine.engine.Engine.onTickUpdate(Engine.java:459) 
    at org.anddev.andengine.engine.Engine$UpdateThread.run(Engine.java:685) 

...這我假設是因爲我在onUpdate()中間取出AnimatedSprite。如何在沒有這個問題的情況下實現我想要的?

回答

5

當從場景中分離精靈時,它應該被分離到runOnUpdateThread()中;

public void onUpdate(float pSecondsElapsed) { 
     if(explosion.getCurrentTileIndex() == 7){ 
      runOnUpdateThread(new Runnable() { 
      @Override     
      public void run() { 
       mScene.detachChild(explosion); 
      } 
      });     
     } 
    } 
相關問題