As of now I've been using Gdx.graphics.getDeltaTime() to achieve this but I think this shouldn't be the correct way.

Let's say I have 3 images/sprites and I want the first one to stay for 1 second, the second sprite for 0.5 second and the third sprite for 3.5 seconds, so it combines a 5 second animation.

As of now I've been using "ifs", as in

if time <= 1 second, draw first image

if time > 1 && time <= 1.5, draw second image

if time > 1.5 && time < 5, draw third image

I've followed 2D Animation tutorial, but to run multiple sprites in order, they all have the same time between them and I want it to have different frametime.

Any idea that might I would be apreciated.

The idea is to run timed based animations for a certain amount of time.


Why not implement your own class? :)

* type T: The type of frame to display (Texture, Sprite, etc.)
class TimedAnimation<T> {
    private T[] frames;
    private float[] frameTimes;

    public TimedAnimation(T[] frames, float[] frameTimes) {
        this.frames = frames;
        this.frameTimes = frameTimes;

    /** Returns the frame that should show after timeElapsed seconds. */
    public Optional<T> getFrame(final float timeElapsed) {
        float counter = timeElapsed;
        float index = 0;
        while(counter > frameTimes[index] && index < frames.length) {
            counter -= frameTimes[index];
        return index < frames.length ? Optional.of(frames[index]) : Optional.empty();

Assumes some things, namely that the size of frames and frameTimes is equal and that timeElapsed is never greater than the total time of the animation. Removing these limitations is practice for the reader ;)

  • \$\begingroup\$ Holy cow that's pretty smart, I think I can work with that. Thanks a lot, you saved me a lot of headaches. \$\endgroup\$ – Nuno Nov 20 '18 at 2:34

One way to achieve variable length frames whilst still getting away with only using standard libGDX functionality would be to insert the same frame multiple times in the animation sequence:

TextureRegion firstImage  = /* loaded somehow */
TextureRegion secondImage = /* loaded somehow */
TextureRegion thirdImage  = /* loaded somehow */

TextureRegion[] frames = new TextureRegion[] {
  /* 2 x 0.5 = 1.0 second */
  firstImage, firstImage,
  /* 1 x 0.5 = 0.5 seconds */
  /* 7 x 0.5 = 3.5 seconds */
  thirdImage, thirdImage, thirdImage, thirdImage, thirdImage, thirdImage, thirdImage

Animation<TextureRegion> animation = new Animation<TextureRegion>(0.5f, frames);

In cases like the one above where it's easy to figure out an animation frame time and the split between the frames this approach is doable, for complex frame time relations it might be harder.

One advantage is that you get all the functionality of Animation<T> such as PlayMode.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.