java—如何在使用javafx animationtimer时获得瞬时fps速率

tcbh2hod  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(313)

我在做一个按照物理定律运行的游戏:即f=ma。游戏中的物体,根据它们所受的力改变它们的速度和位置。
我正在使用animationtimer类。游戏是二维的。
我有一个班级舞会:

public class Ball extends javafx.scene.shape.Circle {
    int m; //mass
    int vX, vY; // velocity componenets

    void feelForce (int forceX, int forceY) {
        vX += forceX * t/m;
        vY += forceY * t/m;
        setCenterX (getCenterX() + vX * t);
        setCenterY (getCenterY() + vY * t);
    }
}

我面临的问题是我不知道如何定义t。每秒的帧数在整个运行时可能会有所不同,我想知道每次如何找到该值 feelforce() 被称为。

public void start(Stage stage) throws Exception {
    //have overridden the constructor in class Ball. Had not shown it to keep it short
    Ball player = new Ball(400.0, 300.0, 30.0, Color.TOMATO); 
    Pane main = new Pane(player);
    Scene scene = new Scene(main);
    stage.setScene(scene);
    stage.show();

    AnimationTimer gamePlay = new AnimationTimer() {
        public void handle(long now){
            player.feelForce(Math.random() * 10, Math.random() * 10);
            // I use MouseEvents to get force values, but have used random numbers here, for brevity
        }
    };
    gamePlay.start();
}

如果使用animationtimer不可能/高效,那么使用另一个类的解决方案也会很受欢迎。
p、 s:我之所以使用animationtimer而不是timeline,是因为不需要固定的速率。

ibrsph3r

ibrsph3r1#

传递给 handle(...) 方法是时间戳,单位为纳秒。因此,您可以计算自上次以来经过的时间量 handle(...) 已调用:

AnimationTimer gamePlay = new AnimationTimer() {

    private long lastUpdate = -1 ;

    public void handle(long now){

        if (lastUpdate == -1) {
            lastUpdate = now ;
            return ;
        }

        double elapsedSeconds = (now - lastUpdate) / 1_000_000_000.0 ;
        lastUpdate = now ;

        player.feelForce(Math.random() * 10, Math.random() * 10, elapsedSeconds);
        // I use MouseEvents to get force values, but have used random numbers here, for brevity
    }
};

然后更新 feelForce(...) 相应的方法:

public class Ball extends javafx.scene.shape.Circle {
    int m; //mass
    int vX, vY; // velocity componenets

    void feelForce (int forceX, int forceY, double t) {
        vX += forceX * t/m;
        vY += forceY * t/m;
        setCenterX (getCenterX() + vX * t);
        setCenterY (getCenterY() + vY * t);
    }
}

相关问题