1

I created a DemoCharSprite object that extends Pane and holds an imageview of the character. I only used the extension of Pane here because I'm novice to Javafx... However, implementing sprite animations is confusing me.

I have a set of 8 png files that showcase an avatar walking north. I've stored them in a Collection object. However, I don't know what data structure I could use that could make it so that javafx loops through each collection and changes the imageview within my DemoCharSprite pane to display each sprite picture in an evenly spaced and short amount of time. There doesn't seem to be any built-in Transition objects that could be used for displaying multiple images in a sequential order.

Does anyone know a workaround for this?

Byron Smith
  • 587
  • 10
  • 32

1 Answers1

4

You can use a timeline as follows:

private int imageIndex = 0 ;
private final int frameTime = ... ; // milliseconds

// ...

ImageView imageView = new ImageView();
List<Image> images = new ArrayList<>();
// populate images...

Timeline timeline = new Timeline(new KeyEvent(Duration.millis(frameTime),
    e -> imageView.setImage(images.get(imageIndex++))));

timeline.setCycleCount(images.size());
timeline.play();

Alternatively, you could just subclass Transition (this is a simple adaptation of the example in the docs):

ImageView imageView = new ImageView();
List<Image> images = new ArrayList<>();
// populate images...

Transition animation = new Transition() {
    {
        setCycleDuration(Duration.millis(1000)); // total time for animation
    }

    @Override
    protected void interpolate(double fraction) {
        int index = (int) (fraction*(images.size()-1));
        imageView.setImage(images.get(index)); 
    }
}
animation.play();
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Thank you. This is working exactly as desired. I was reading documentation all day but to be honest I couldn't quit determine how Keyframes could be initialized to get the behavior I wanted. – Byron Smith Dec 18 '17 at 21:36