问题
I'm developing a simple Java videogame. I've decided to shape the characters of that videogame by using the Rectangle class of JavaFX.
When a character dies, I need to update the texture sequentially, until the death of the characters. I need to realize an animation for this reason.
I've tried to use the FillTransition, but I can't change the filling Image of the rectangle but only the color...what kind of animation class should I use?
The death of a character is represented by 4 different sprites (four png images) which shows the character laying down to the soil gradually. I need to change the filling of the rectangle with these 4 images sequentially, while the character is dying.
回答1:
Rectangle is not a good node type to do this kind of stuff. It's much simpler to use ImageView for this purpose.
This allows you do use a Timeline for manipulation of the image property of the ImageView:
final Image[] deathAnimationImages = new Image[] {...};
final ImageView character = ...;
Duration frameDuration = Duration.seconds(1d / deathAnimationImages.length); // 1 second for complete animation
Timeline deathAnimation = new Timeline(new KeyFrame(frameDuration, new EventHandler<ActionEvent>() {
private int index = 0;
@Override
public void handle(ActionEvent event) {
character.setImage(deathAnimationImages[index]);
index++;
}
}));
deathAnimation.setCycleCount(deathAnimationImages.length);
deathAnimation.play();
If you use Rectangle + ImagePattern to get a image of a given size you can produce the same result using ImageView.fitWidth and ImageView.fitHeight.
来源:https://stackoverflow.com/questions/51610670/how-to-change-the-fill-of-an-object-in-a-javafx-animation