Reputation: 1238
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?
Upvotes: 12
Views: 9567
Reputation: 48
I didn't want to create another class so this is what I came up with this instead (If you just want a simple animated Actor):
Actor animatedActor = new Actor() {
float time;
@Override
public void act( float delta ) {
time += delta;
super.act(delta);
}
@Override
public void draw( Batch batch, float parentAlpha ) {
batch.draw( searcAnimation.getKeyFrame( time ), getX(), getY(), getWidth(), getHeight() );
}
};
animatedActor.setSize( 200, 200 );
stage.addActor( animatedActor );
Hopes this helps!
Upvotes: -1
Reputation: 1668
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);
}
}
Upvotes: 13
Reputation: 221
I simply created an "AnimatedImage" actor class which only takes an Animation as an argument (no need for a custom Drawable class). I think this solution is much simpler than the one above.
AnimatedImage.java:
public class AnimatedImage extends Image
{
protected Animation animation = null;
private float stateTime = 0;
public AnimatedImage(Animation animation) {
super(animation.getKeyFrame(0));
this.animation = animation;
}
@Override
public void act(float delta)
{
((TextureRegionDrawable)getDrawable()).setRegion(animation.getKeyFrame(stateTime+=delta, true));
super.act(delta);
}
}
Upvotes: 22