Java 射击多发子弹时的图形问题

Java Graphic trouble when shooting multiple bullet

所以我正在尝试创建这个 java 关于飞机射击外星人和东西的游戏。每次单击鼠标,飞机都会发射一颗子弹。这意味着飞机一次可以发射 10 发或 20 发或更多子弹。为了演示子弹运动,我尝试了 Thread 和 Timer,但真正的问题是,如果我射出 1 颗子弹,这意味着我创建了一个新的 Thread(或 Timer),这会使游戏 运行 非常慢。有什么办法可以解决这个问题吗? 这是我的子弹移动代码

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<>();

在该线程的运行方法中,您可以连续更新所有项目符号:

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);
}

然后您可以调用它来添加新项目符号,主线程将更新该项目符号以及所有其他项目符号。