【问题标题】:How can I create a sprite run cycle in JavaFX?如何在 JavaFX 中创建精灵运行周期?
【发布时间】:2019-08-15 22:14:05
【问题描述】:

所以,我正在尝试使用 JavaFX 创建游戏。我知道大部分基础知识,但我对如何在 JavaFX 中创建精灵运行周期感到困惑。

精灵表:https://imgur.com/K2nHT23

我希望能够使用一种方法调用运行周期,例如:

public static void runCycle(){
// execute run cycle, I think the Animation class may help here?
// move image as well, I got that nailed down already though.
}

我知道这不是 MRE,但我正在尝试集思广益,所以如果您有任何建议,请告诉我! :)

链接的图像是精灵表,如果有人可以帮助我解决这个问题,那就太好了。谢谢!

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    您需要定期更新 UI 以实现此目的。您如何执行此操作取决于您对其余更新进行编码的方式。如果您使用AnimationTimer 创建游戏循环,这可能是进行这些更新的好地方,但对于单个图像,Timeline 似乎最方便。

    如何更新 GUI 取决于您想要绘制图像的方式。 Canvas 需要与 ImageView 不同的处理方式。前者需要您使用drawImage 方法,允许您指定要绘制的源图像的部分,后者需要您更新viewport 属性。

    以下示例展示了如何为此目的使用ImageViewTimeline

    @Override
    public void start(Stage primaryStage) throws Exception {
        Image image = new Image("https://i.imgur.com/K2nHT23.png");
        int height = 4;
        int width = 2;
        double spriteHeight = image.getHeight() / height;
        double spriteWidth = image.getWidth() / width;
    
        // create viewports to cycle through
        List<Rectangle2D> areas = new ArrayList<>(height * width);
    
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                areas.add(new Rectangle2D(x * spriteWidth, y * spriteHeight, spriteWidth, spriteHeight));
            }
        }
    
        ImageView imageView = new ImageView(image);
        imageView.setViewport(areas.get(0));
    
        // create timeline animation cycling through viewports
        Timeline timeline = new Timeline(new KeyFrame(Duration.millis(1000d / 6), new EventHandler<ActionEvent>() {
    
            int index = 0;
    
            @Override
            public void handle(ActionEvent event) {
                imageView.setViewport(areas.get(index));
                index++;
                if (index >= areas.size()) {
                    index = 0;
                }
            }
    
        }));
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();
    
        Scene scene = new Scene(new StackPane(imageView));
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    (不确定这是否是动画中所需的精灵顺序。)

    【讨论】:

    • 谢谢!这完美!为我节省了很多故障排除哈哈。感谢您的帮助,非常感谢您:)
    猜你喜欢
    • 2013-10-13
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    相关资源
    最近更新 更多