【问题标题】:JavaFX and sprite animation, how do I make an animation cycle to change pictures of my playersprite?JavaFX和精灵动画,我如何制作动画循环来改变我的玩家精灵的图片?
【发布时间】:2018-06-01 06:19:11
【问题描述】:

我创建了一个 DemoCharSprite 对象,它扩展了 Pane 并保存了角色的图像视图。我在这里只使用了 Pane 的扩展,因为我是 Javafx 的新手……但是,实现精灵动画让我感到困惑。

我有一组 8 个 png 文件,展示了一个向北行走的化身。我已将它们存储在 Collection 对象中。但是,我不知道我可以使用什么数据结构,以便 javafx 循环遍历每个集合并更改我的 DemoCharSprite 窗格中的图像视图,以在均匀间隔和短时间内显示每个精灵图片。似乎没有任何内置的过渡对象可用于按顺序显示多个图像。

有人知道解决方法吗?

【问题讨论】:

标签: java animation javafx


【解决方案1】:

您可以按如下方式使用时间线:

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();

或者,您可以只继承 Transition(这是对文档中示例的简单改编):

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();

【讨论】:

  • 谢谢。这完全按预期工作。我整天都在阅读文档,但老实说,我无法确定如何初始化关键帧以获得我想要的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 2018-08-20
相关资源
最近更新 更多