Search code examples
javaanimationlibgdx

How to play an animation frames for once each time?-LibGdx


I'm using an animation with 6 frames in my game for an event. It has a fixed order to be played.

Array<TextureAtlas.AtlasRegion> anim=new Array<TextureAtlas.AtlasRegion>();
anim =  game.playAtlas.findRegions(RegionNames.FEATHER_ANIMATION);
TextureRegion[] ftr = {anim.get(0),anim.get(1),anim.get(2),anim.get(3),anim.get(4),anim.get(5)};

featherAnimation = new Animation(0.1f,ftr);
featherAnimation.setPlayMode(PlayMode.NORMAL);

I want to run this animation only once(that means it should play 0th frame to last frame and then should stop),when a particular boolean is true.

After playing the last frame,It should stop and make the boolean false also.

Like this I did

if (featherBool && egg.isEggAtNest()) {
  featherTexture = featherAnimation.getKeyFrame(animationTime, true);
  batch.draw(featherTexture, egg.getX() - featherTexture.getRegionWidth() / 2, fx.getY());
  featherBool = false;
}

But this is not achieving what I want.

The frames are not in the order I specified. Also, how can I stop the animation once it plays 0 to 5th frame?


Solution

  • Use in this way :

    if (featherBool) {  
        animationTime+=.01f;
        featherTexture = featherAnimation.getKeyFrame(animationTime);  // <--looping not required so remove second argument
        batch.draw(featherTexture, egg.getX() - featherTexture.getRegionWidth() / 2, fx.getY());
        if(featherAnimation.isAnimationFinished(animationTime))
            featherBool = false;
    }
    

    Call showAnimation() method

    private void showAnimation(){
    
        featherBool=true;
        animationTime=0;
    }