【发布时间】:2011-10-12 23:25:38
【问题描述】:
我在我的游戏中使用了 Swing Timer,但是当游戏运行时,它似乎有运行平稳的时刻和减慢速度的时刻。
为什么时间会波动?
我该如何解决?
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JFrame {
public Main() {
super("JFrame");
// you can set the content pane of the frame
// to your custom class.
setContentPane(new ImagePanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 400);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main();
}
class ImagePanel extends JPanel {
Timer movementtimer;
int x, y;
public ImagePanel() {
x = 0;
y = 0;
movementtimer = new Timer(12, new ActionListener() {
public void actionPerformed(ActionEvent e) {
long timstarted = System.currentTimeMillis();
moveImage();
repaint();
long timefinished = System.currentTimeMillis() - timstarted;
System.out.println(timefinished + " to run");
};
});
movementtimer.start();
}
public void moveImage() {
x++;
y++;
if (x > 800) {
x = 0;
}
if (y > 400) {
y = 0;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(0, 0, 800, 400);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 50);
}
}
}
这是我的代码示例。在我的实际程序中,我正在绘制图像而不仅仅是一个矩形。还有很多碰撞检测和其他小计算发生。
另外,这里是游戏 Jar 文件的链接,您可以运行它并(希望)明白我的意思。 http://dl.dropbox.com/u/8724803/Get%20To%20The%20Chopper%201.3.jar
谢谢
汤姆
【问题讨论】:
-
顺便说一句 - 我无法理解您的计时计算逻辑。将
long timstarted;设为ActionListener类的属性,您可能会看到我所看到的 - 一致的 12s 和 13s。