2016-04-21 61 views
1

所以我想创建这个关于飞机射击外星人和东西的java游戏。每次点击鼠标时,飞机都会发射子弹。这意味着飞机一次可以发射10或20发或更多的子弹。为了演示子弹运动,我尝试了线程和计时器,但真正的问题是如果我1子弹击出意味着我创建了一个新的线程(或计时器),并使游戏运行非常缓慢。有什么办法可以解决这个问题吗? 这里我的代码为子弹移动Java图形故障时,拍摄多个子弹

public class Bullet extends JComponent implements Runnable { 

int x;//coordinates 
int y; 
BufferedImage img = null; 
Thread thr; 
public Bullet(int a, int b) { 
     x = a; 
     y = b; 
     thr = new Thread(this); 
     thr.start(); 

    } 
protected void paintComponent(Graphics g) { 
     // TODO Auto-generated method stub 
     try { 
      img = ImageIO.read(new File("bullet.png")); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     // g.drawImage(resizeImage(img, 2), x, y, this); 

     g.drawImage(Plane.scale(img, 2, img.getWidth(), img.getHeight(), 0.125, 0.125), x, y, this); 
     width = img.getWidth()/8; 
     height = img.getHeight()/8; 

     super.paintComponent(g); 

    } 
public void run() { 


     while(true) 
     { 
      if(y<-50)break;//if the bullet isnt out of the frame yet 
      y-=5;//move up 
      repaint(); 
      try { 
       Thread.sleep(10); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 

    } 

} 
+1

创建一个包含项目符号的x,y位置的Bullet类。为每个子弹创建一个Bullet实例。将Bullet的实例保存在列表中。创建** one **线程来更新项目符号的位置,并通过迭代Bullet对象列表来在屏幕上绘制项目符号。从paintComponent方法中读取子弹图像的读数。首先调用super.paintComponent。聘请导师教你适当的Java Swing编码。 –

回答

1

子弹不应该在自己的线程。这有几个原因,其中之一是你提到的 - 这会让你的游戏非常缓慢。

尝试使用一个主线程更新所有项目符号。您将需要一个更新功能在你的子弹:

public class Bullet extends JComponent { 
public void update() { 
    if(y<-50)return; //if the bullet isnt out of the frame yet 
    y-=5;   //move up 
} 

//all your other code for your bullet 
} 
在你的主线程

然后让子弹列表:

LinkedList<Bullet> bullets = new LinkedList<>(); 

在该线程的run方法,你可以不断地更新所有的子弹:

public void run() { 
    while(true) 
    { 
     for (Bullet b : bullets) { 
      b.update(); 
     } 
     repaint(); 
     try { 
      Thread.sleep(10); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

你需要有一种方法在你的主线程,可以让你添加一个新的子弹:

public void addBullet(Bullet b) { 
    bullets.add(b); 
} 

然后你可以调用它来添加一个新的项目符号,主线程将会更新这个项目符号以及所有其他项目。

+0

非常感谢。我现在得到它 – Anonymous

+0

如果我的答案帮助它将是很好,如果你upvoted和/或接受它。 – nhouser9