繁体   English   中英

射击多颗子弹时出现Java图形问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM