我正在用 Java 创建一个需要帧动画的游戏程序,并且需要每 40 毫秒重新绘制一次帧。但是,我不太确定如何让 Timer 处理这些重绘。我试过这样的事情:
Timer timer = new Timer(null);
但是我想我需要在初始化程序中设置更新时间,对吗?我该如何去做,并在程序启动时让计时器运行?或者干脆就跑?我知道 null 不可能是正确的。帮助将不胜感激。
Timer timer = new Timer(50, this);
timer.start();
“50”是计时器关闭的频率,以毫秒为单位。...这调用了一个 actionListener
public void actionPerformed(ActionEvent e){
//do stuff here
}
....然后停止计时器
timer.stop();
一个例子:
class MyPanel extends JPanel implements ActionListener{
public Timer time1;
public MyPanel() {
time1 = new Timer(40,this);
setBorder(BorderFactory.createLineBorder(Color.black));
}
public void actionPerformed (ActionEvent e){
//do stuff here
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//your paint method
}
}
Timer t = new Timer(delay, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Do your Stuff here
}
});
t.start();
其中 delay 是整数值,它以毫秒为单位显示计时器的延迟,并在您希望时停止计时器
t.stop();
您需要构建具有延迟的计时器和自定义动作侦听器。
class TimerAction implements ActionListener{
boolean isItTimeForTic = true;
@Override public void actionPerformed(ActionEvent e) {
//this is the place to define logic which will be invoked after every DELAY ms
}
}
然后你像这样使用它:
int delay = 1; //you set your delay here
Timer timer = new Timer(delay, new TimerAction());
timer.start();
如果您希望您的计时器重新绘制一个框架,您可以修改您的 TimerAction 以引用框架,然后在 actionPerformed 中调用它的方法。
如果你正在创建一个游戏,你必须已经实现了 runnable。所以我建议你做类似的事情。
//1
private boolean running = true;
private long fps = 0;
// private static final int MAX_CPS = 50;
// private static final long MS_PER_FRAME = 1000 / MAX_CPS;
private static final long MS_PER_FRAME = 40;//in your case it is 40//cps is 25
public void run(){
while(running){
long cycleStartTime = System.currentTimeMillis();
gameUpdate();//for updating your game logic
repaint();//for stuff like painting
long timeSinceStart = (cycleStartTime - System.currentTimeMillis());
if(timeSinceStart < MS_PER_FRAME){
try{
fps = MS_PER_FRAME - timeSinceStart;
Thread.sleep(fps);
}catch(InterruptedException e){
System.err.println("InterruptedException in run "+e);
}catch(Exception e){
System.err.println("Exception in run "+e);
}
}//closig if
}//closing while
}//closing run
//Like in your case you want to paynt after constant time you can do somehting like
//2
// private static final int MAX_CPS = 25;
private static final long MS_PER_FRAME = 40
public void run(){
while(running){
gameUpdate();//for updating your game logic
repaint();//for stuff like painting
try{
Thread.sleep(MS_PER_FRAME);
}catch(InterruptedException e){
System.err.println("InterruptedException in run "+e);
}catch(Exception e){
System.err.println("Exception in run "+e);
}
}//closig if
}//closing while
}//closing run
我建议使用 1,因为它可以让游戏更加流畅