Patryk Kownacki
Patryk Kownacki

Reputation: 17

How to move a node with AnimationTimer?

I want to move a rectangle across the screen using AnimationTimer. I want to do this, because I want to learn how AnimationTimer works, so I can make a game with it. I am currently having issues with doing so.

public class FXTimer extends Application {


    @Override
    public void start(Stage primaryStage) {

        Rectangle rect = new Rectangle(1000,100,100,100);

        AnimationTimer timer = new AnimationTimer(){
            @Override
            public void handle(long now) {
                rect.relocate(rect.getLayoutX()-10, 100);
            }      
        };

        //root.getChildren().addAll(rect);
        timer.start();


        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(new Scene(new Group(rect),1000,1000));
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

Upvotes: 0

Views: 452

Answers (1)

c0der
c0der

Reputation: 18792

Here is a simple example (mvce : copy, paste, run). Note the comments :

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class FXTimer extends Application {

    @Override
    public void start(Stage primaryStage) {

        Rectangle rect = new Rectangle(0,0,10,10); //make is small so you can see it move
        rect.setFill(Color.BLUE); //set distinc color so you can see it move
        AnimationTimer timer = new AnimationTimer(){
            @Override
            public void handle(long now) {
                rect.setTranslateX(rect.getTranslateX()+ 1);
                //rect.relocate(rect.getLayoutX() +10, 100); //relocate does not change translateX or translateY
            }
        };

        timer.start();

        primaryStage.setTitle("AnimationTimer Demo");
        primaryStage.setScene(new Scene(new Group(rect),300,100));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here

Upvotes: 3

Related Questions