Search code examples
javalibgdx

LibGDX is there an actor that is animated?


In LibGDX Is there an actor that is animated (takes an Animation) and when added to a Stage animates itself or do you have to implement your own Image class in and animate it yourself?


Solution

  • Just like you I didn't find animated Actor so I created myself:

    AnimatedActor.java:

    public class AnimatedActor extends Image
    {
        private final AnimationDrawable drawable;
    
        public AnimatedActor(AnimationDrawable drawable)
        {
            super(drawable);
            this.drawable = drawable;
        }
    
        @Override
        public void act(float delta)
        {
            drawable.act(delta);
            super.act(delta);
        }
    }
    

    AnimationDrawable.java:

    class AnimationDrawable extends BaseDrawable
    {
        public final Animation anim;    
        private float stateTime = 0;
    
        public AnimationDrawable(Animation anim)
        {
            this.anim = anim;
            setMinWidth(anim.getKeyFrameAt(0).getRegionWidth());
            setMinHeight(anim.getKeyFrameAt(0).getRegionHeight());
        }
    
        public void act(float delta)
        {
            stateTime += delta;
        }
    
        public void reset()
        {
            stateTime = 0;
        }
    
        @Override
        public void draw(SpriteBatch batch, float x, float y, float width, float height)
        {
            batch.draw(anim.getKeyFrame(stateTime), x, y, width, height);
        }
    }