Warm tip: This article is reproduced from serverfault.com, please click

java-使用Javafx AnimationTimer时如何获得瞬时fps速率

(java - How to get the instantaneous fps rate when using Javafx AnimationTimer)

发布于 2020-11-30 07:11:35

我正在制作根据物理定律运行的游戏:F = ma。游戏中的物体会根据其承受的力来改变其速度和位置。
我正在使用AnimationTimer类。游戏是二维的。
我有一个Ball课:

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不可能/高效,那么使用其他类的解决方案也将不胜感激。
PS:之所以我使用AnimationTimer而不是时间轴,是因为没有必要使用固定速率。

Questioner
febot
Viewed
0
James_D 2020-11-30 21:19:23

传递给该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);
    }
}