在这里,我正在尝试使用秋千和计时器在Java中制作赛车游戏,但我知道我应该使用线程来做。
如何将基于计时器的应用程序转换为基于线程的应用程序?我还认为我可以使用多线程在随机时间以随机速度绘制一些敌人,或者无论如何我可以使用一个计时器或一个线程来做到这一点?(我也知道计时器使用自己的线程。)
我已经尝试在相应行中启动线程而不是计时器。
感谢所有帮助:)
public class GamePanel extends JPanel {
Motor p;
public Image img1,img2,img3;
Timer time;
int ptm=1000000000;
boolean running = true;
Graphics2D g2d;
Graphics g2;
public GamePanel() {
p = new Motor();
setFocusable(true);
ImageIcon background = new ImageIcon("D:/Desktop/backgorund.jpg");
ImageIcon background2 = new ImageIcon("D:/Desktop/backgorund2.jpg");
ImageIcon motor = new ImageIcon("D:/Desktop/HANGONIMAGE/Motor.png");
ImageIcon mountains = new ImageIcon();
img1 = background.getImage();
img2 = background2.getImage();
img3 = motor.getImage();
time= new Timer(5, gameLoop);
time.start();
}
public void addNotify(){
super.addNotify();
addKeyListener(new KeyMonitor(p));
}
private ActionListener gameLoop = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
p.uptade();
repaint();
}
};
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
Graphics2D speed = (Graphics2D) g;
Graphics2D score = (Graphics2D) g;
if(p.up) //SPEED
p.speed++;
if(p.down || !p.up)
p.speed--;
if(p.speed==-1)
p.speed++;
if(p.speed>=600)
p.speed=600;
if((p.speed%2==1 && p.speed>0 )) {
g2d.drawImage(img2,p.getX(),p.getY(),null); //background
}
else
g2d.drawImage(img1,p.getX(),p.getY(),null); //background
if(p.speed>=500)
g2d.drawImage(img3,200,200,null);
g2d.drawImage(p.getImage(),265,320,null); //player motor
//SPEED
speed.setFont(new Font("Segoe Script", Font.BOLD + Font.ITALIC,20));
speed.setPaint(Color.ORANGE);
speed.drawString("SPEED : "+p.speed, 560, 40);
//SCORE
score.setFont(new Font("Algerian", Font.BOLD + Font.ITALIC, 20));
score.setPaint(Color.RED);
if(p.speed < 30)
p.score += p.speed/20;
else
p.score += p.speed/30;
speed.drawString("SCORE: "+p.score, 20, 40);
}
}