如何在使用Javafx AnimationTimer时获得瞬时fps速率
我正在做一个按照物理定律运行的游戏:即F=ma。游戏中的物体,根据它们所受的力改变它们的速度和位置。如何在使用Javafx AnimationTimer时获得瞬时fps速率,java,animation,javafx,Java,Animation,Javafx,我正在做一个按照物理定律运行的游戏:即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) {
我正在使用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不可能/有效,那么使用另一个类的解决方案也将受到欢迎注:我之所以使用AnimationTimer而不是Timeline,是因为不需要固定速率。
传递给
句柄(…)
方法的值是时间戳,单位为纳秒。因此,您可以计算自上次调用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);
}
}
传递给
句柄(…)
方法的值是时间戳,单位为纳秒。因此,您可以计算自上次调用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);
}
}