Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the speed of an AnimationTimer in JavaFX?

I'm trying to change the speed of an AnimationTimer so the code runs slower, here is the code I have so far:

AnimationTimer timer = new AnimationTimer() {

    @Override
    public void handle(long now) {    
        if (upOrDown != 1) {
            for (int i = 0; i < 4; i++) {
                snakePositionDown[i] = snake[i].getX();
                snakePositionDownY[i] = snake[i].getY();
            }

            snake[0].setY(snake[0].getY() + 25);

            for (int i = 1; i < 4; i++) {
                snake[i].setX(snakePositionDown[i - 1]);
                snake[i].setY(snakePositionDownY[i - 1]);
            }

            leftOrRight = 2;
            upOrDown = 0;
        }
    }

};

timer.start();

How would I make the AnimationTimer run slower?

Thanks in advance!

like image 511
JohnIsCool222 Avatar asked May 14 '18 19:05

JohnIsCool222


1 Answers

You could use a Timeline for this purpose. Adjusting the Timeline.rate property also allows you to update the "speed":

// update once every second (as long as rate remains 1)
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {

    if (upOrDown != 1) {
        for (int i = 0; i < 4; i++) {
            snakePositionDown[i] = snake[i].getX();
            snakePositionDownY[i] = snake[i].getY();
        }
        snake[0].setY(snake[0].getY() + 25);
        for (int i = 1; i < 4; i++) {
            snake[i].setX(snakePositionDown[i - 1]);
            snake[i].setY(snakePositionDownY[i - 1]);
        }
        leftOrRight = 2;
        upOrDown = 0;
    }    

}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

...

// double speed
timeline.setRate(2);
like image 74
fabian Avatar answered Sep 21 '22 10:09

fabian