[英]Java Graphic trouble when shooting multiple bullet
So i'm trying to create this java game about aircraft shooting aliens and stuff.所以我正在尝试创建这个关于飞机射击外星人之类的 Java 游戏。 The aircraft shoot a bullet every time mouse click.每次鼠标点击,飞机就会发射一颗子弹。 That mean the aircraft can shoot 10 or 20 or more bullets at a time.这意味着飞机一次可以发射 10 颗或 20 颗或更多子弹。 To demonstrate the bullet movement i tried Thread and Timer but the real problem is if i 1 bullet shot out that mean i created a new Thread(or Timer) and that make the game run very slow.为了演示子弹运动,我尝试了线程和计时器,但真正的问题是,如果我射出 1 颗子弹,这意味着我创建了一个新的线程(或计时器),这会使游戏运行速度非常慢。 Is there any way i can fix this problem?有什么办法可以解决这个问题吗? Here a my code for bullet moving这是我的子弹移动代码
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();
}
}
}
}
A bullet should NOT be on its own thread.子弹不应该在它自己的线程上。 There are several reasons for this, one of which is the one you mentioned - it is going to make your game very slow.造成这种情况的原因有很多,其中之一就是你提到的——它会让你的游戏变得很慢。
Try using one master thread which updates all bullets.尝试使用一个主线程来更新所有项目符号。 You will need an update function in your bullet:您的项目符号中将需要一个更新功能:
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
}
Then in your master thread have a list of bullets:然后在您的主线程中有一个项目符号列表:
LinkedList<Bullet> bullets = new LinkedList<>();
In the run method of that thread, you can continuously update ALL bullets:在该线程的 run 方法中,您可以不断更新所有项目符号:
public void run() {
while(true)
{
for (Bullet b : bullets) {
b.update();
}
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You will need to have a method in your master thread that lets you add a new bullet:您需要在主线程中有一个方法来添加新项目符号:
public void addBullet(Bullet b) {
bullets.add(b);
}
Then you can call that to add a new bullet and the master thread will update that bullet along with all the others.然后你可以调用它来添加一个新的项目符号,主线程将与所有其他项目一起更新该项目符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.