有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在JavaFX中创建sprite运行周期?

所以,我正在尝试使用JavaFX创建一个游戏。我知道大部分的基础知识,但我不知道如何在JavaFX中创建一个sprite运行周期

精灵表: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,但我正试图集思广益,所以如果你有任何建议,请让我知道!:)

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


共 (1) 个答案

  1. # 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();
    }
    

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