当前位置: 动力学知识库 > 问答 > 编程问答 >

Increasing speed of Timer in Java

问题描述:

I'm making a game with Java and I'm currently using Timers for all my animations and game controls. But I'm having trouble choosing the right way to increase the speed of a Timer. My game is supposed to get faster and faster as the game progresses, and I'm finding that there are many ways to increase the speed of my objects, but I'm not sure which one is the most efficient to use.

For example, let's say the int xpos is the variable the increments the xposition of an object.

Timer timer = new Timer(100, new ActionListener() //01

{ //02

public void actionPerformed(ActionEvent e) //03

{ //04

xpos++; //05

repaint(); //06

} //07

} //08

//09

timer.start(); //10

To increase the speed of this, I could increase the incrementation of xpos on line 5 to xpos+=2.

I could also increase the speed by decreasing the millisecond parameter for the Timer to: Timer timer = new Timer(50, new ActionListener() on line 1.

Or I could add a second Timer that would do the same task to double the speed of the timer. Basically, I could do this:

Mover mover = new Mover();

Timer timer = new Timer(100, mover);

Timer timer2 = new Timer(100, mover);

timer.start();

timer2.start();

class Mover implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

xpos++;

repaint();

}

}

Which one do you think would be most effective? Or should I combine all these techniques? Thanks for any replies.

网友答案:
  • Keep the Timer beat steady, invariant.
  • Store your logical position and velocity with doubles or Point2D.Double.
  • Don't rely on the accuracy of the timer interval.
  • Calculate change in position based on velocity and change in system time.
分享给朋友:
您可能感兴趣的文章:
随机阅读: