我正在尝试计算增量时间,以便无论帧速率如何都能在屏幕上平滑移动圆圈。当我运行我的代码时,圆圈抖动意味着增量时间没有正确计算但我在计算中找不到错误。这是代码
主类
import javax.swing.JFrame;
public class Main {
public static long lastTime;
public static double deltaTime;
public static void main(String[] args) {
lastTime = 0;
//Setting up the JFrame
JFrame frame = new JFrame("Test");
frame.setSize(600, 400);
frame.add(new PanelP());
frame.setVisible(true);
//Loop
while(true) {
//Calculate DeltaTime
deltaTime = (lastTime - (lastTime = System.nanoTime())) / -1000000.0;
//Draw Frame
frame.repaint();
}
}
}
Panel类
import java.awt.Graphics;
import javax.swing.JPanel;
public class PanelP extends JPanel{
private float x;
public PanelP() {
super();
}
@Override
public void paintComponent(Graphics g) {
//Move circle
x += (10 * (float)Main.deltaTime);
//Draw Circle
g.drawOval(Math.round(x), 50, 30, 30);
}
}
答案 0 :(得分:0)
lastTime = 0;
可能是一个错误,所以我会修复它。请改为使用System.nanoTime()
进行初始化。
您也可以尽可能快地更新。我使用SwingTimer
甚至只是Tread.sleep()
来降低速度,以便屏幕有时间实际显示。每秒尝试20次。