fredley
fredley

Reputation: 33931

How do I make an AnimatedSprite play once then remove itself?

I have a method makeExplosion:

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() {

        }});
}

..which does not work. I get the following error:

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)

...which I'm assuming is because I'm removing the AnimatedSprite in the middle of its onUpdate(). How can I acheive what I want without this problem?

Upvotes: 3

Views: 2336

Answers (1)

stackuser
stackuser

Reputation: 239

while detach sprite from the scene it should be detached inside of runOnUpdateThread();

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

Upvotes: 5

Related Questions