下面是一些代码。我首先创建了一个名为 Bullet 的类。这是应该加载图像的位置。
package gameLibrary;
import java.awt.*;
import javax.swing.ImageIcon;
public class Bullet {
int x,y;
Image img;
boolean visible;
public Bullet(int startX, int startY) {
x = startX;
y = startY;
ImageIcon newBullet = new ImageIcon("/resources/bullet.png");
img = newBullet.getImage();
System.out.println("constructor Bullet is called");
visible = true;
}
public void move(){
x = x + 1;
if(x > 854){
System.out.println("Bullet is moving at X = " + x);
visible = false;
}
}
public int getX(){
return x;
}
public int getY() {
return y;
}
public boolean getVisible(){
return visible;
}
public Image getImage(){
return img;
}
}
当按下空格键时,它会调用一个名为 fire() 的方法,其中有一个 new Bullet(X, Y);被调用,然后将其存储在 ArrayList 中。
public void fire(){
if(ammo > 0) {
Bullet z = new Bullet(left + 60, y + 70);
bullets.add(z);
ammo--;
}
}
public static ArrayList getBullets(){
return bullets;
}
此代码在屏幕上移动项目符号。
ArrayList bullets = Character.getBullets();
for(int i = 0; i < bullets.size(); i++){
Bullet m = (Bullet) bullets.get(i);
if(m.getVisible() == true){
m.move();
}if(m.getVisible() == false) {
bullets.remove(i);
}
}
最后是打印方法的代码。
ArrayList bullets = Character.getBullets();
for(int i = 0; i < bullets.size(); i++){
Bullet m = (Bullet) bullets.get(0);
g2d.drawImage(m.getImage(),m.getX(),m.getY(), null);
}
我找不到我哪里出错了。据我所知,子弹的功能全部正常工作,它只是在屏幕上打印图像。非常感谢任何建议。
最佳答案
通常资源是通过Class.getResource加载的
ImageIcon newBullet = new ImageIcon(Bullet.class.getResource("resources/bullet.png"));
当然,资源文件夹应该与您的 Bullet 类位于同一包中(即同一文件夹中)。 无论您的游戏是否在 jar 中,该代码都应该始终有效。
关于java - 2D 滚动游戏 : Firing Bullets. 一切正常,只是没有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19259640/