使JavaFX应用程序在动画之间等待

使JavaFX应用程序在动画之间等待

本文介绍了使JavaFX应用程序在动画之间等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaFX开发一个简单的游戏。我想要的是在循环结束时,应用程序等待指定的时间,然后再次运行。

I am working on a simple game using JavaFX. What I want here is that at the end of the loop, the application waits for a specified period of time, and then runs again.

当我在应用程序线程,视图不会更新,并且在没有我看到动画的情况下节点也会消失。

When I run this code on the application thread, the view doesn't get updated and the Nodes disappear without me seeing the animation.

如果我创建一个新线程,那么什么也不会发生。由于该动画要等到游戏完成后才能运行,因此在动画完成前是否没有其他效果没有关系。

If I create a new thread, then nothing happens at all. Since this animation isn't run until the game has been completed, it doesn't matter if nothing else works until the animation is completed.

下面是我的代码,感谢您的帮助。

Below is my code and any help is appreciated.

private void playWonAnimation(){
    Random rand = new Random();
    for (Node block: tower02List) {
        double xTrans = rand.nextInt(800) + 700;
        double yTrans = rand.nextInt(800) + 700;

        TranslateTransition translate = new TranslateTransition(Duration.millis(2500), block);
        xTrans = (xTrans > 1100) ? xTrans : -xTrans;
        translate.setByX(xTrans);
        translate.setByY(-yTrans);

        RotateTransition rotate = new RotateTransition(Duration.millis(1200), block);
        rotate.setByAngle(360);
        rotate.setCycleCount(Transition.INDEFINITE);

        ParallelTransition seq = new ParallelTransition(translate, rotate);
        seq.setCycleCount(1);
        seq.play();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


推荐答案

将所有动画放入 SequentialTransition ,用 PauseTransition s分隔:

Put all the animations into a SequentialTransition, separated by PauseTransitions:

private void playWonAnimation(){
    Random rand = new Random();
    SequentialTransition seq = new SequentialTransition();
    for (Node block: tower02List) {
        double xTrans = rand.nextInt(800) + 700;
        double yTrans = rand.nextInt(800) + 700;

        int translateTime = 2500 ;
        int oneRotationTime = 1200 ;

        TranslateTransition translate = new TranslateTransition(Duration.millis(translateTime), block);
        xTrans = (xTrans > 1100) ? xTrans : -xTrans;
        translate.setByX(xTrans);
        translate.setByY(-yTrans);

        RotateTransition rotate = new RotateTransition(Duration.millis(translateTime), block);
        rotate.setByAngle(360 * translateTime / oneRotationTime);

        seq.getChildren().add(new ParallelTransition(translate, rotate));
        seq.getChildren().add(new PauseTransition(Duration.seconds(1.0)));
    }

    seq.play();
}

这篇关于使JavaFX应用程序在动画之间等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:34