爪哇三角洲时间会导致运动抖动



我正在尝试计算增量时间,以便无论帧速率如何,都能在屏幕上平滑地移动圆圈。当我运行代码时,圆圈抽搐,这意味着增量时间计算不正确,但我在计算中找不到错误。这是代码

主类

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();
}
}
}

和面板类

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);
}
}
  1. lastTime = 0;可能是一个错误,所以我会修复它。改为使用System.nanoTime()对其进行初始化。

  2. 您也在尽可能快地更新。我会使用SwingTimer甚至只是Tread.sleep()来减慢速度,以便屏幕有时间实际显示。尝试每秒 20 次以启动。

最新更新