[英]Java Graphic trouble when shooting multiple bullet
所以我正在嘗試創建這個關於飛機射擊外星人之類的 Java 游戲。 每次鼠標點擊,飛機就會發射一顆子彈。 這意味着飛機一次可以發射 10 顆或 20 顆或更多子彈。 為了演示子彈運動,我嘗試了線程和計時器,但真正的問題是,如果我射出 1 顆子彈,這意味着我創建了一個新的線程(或計時器),這會使游戲運行速度非常慢。 有什么辦法可以解決這個問題嗎? 這是我的子彈移動代碼
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();
}
}
}
}
子彈不應該在它自己的線程上。 造成這種情況的原因有很多,其中之一就是你提到的——它會讓你的游戲變得很慢。
嘗試使用一個主線程來更新所有項目符號。 您的項目符號中將需要一個更新功能:
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);
}
然后你可以調用它來添加一個新的項目符號,主線程將與所有其他項目一起更新該項目符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.