如何让玩家发射子弹?

我正在创建2D无尽的跑步者,并希望玩家向敌人发射子弹。这是我尝试的代码,但是在加载游戏时,它可以运行,但玩家不会射击。我需要更改/实施什么?

这只是与项目符号相关的代码。

播放状态类:

private ArrayList<Bullet> bullets = new ArrayList<Bullet>();

@Override
 public void onKeyPress(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
        player.jump();
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        player.duck();
    }
    else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
        player.shoot();
    }
}

//TODO added graphics variable and initiate
ArrayList Bullet = player.getBullets();{
for (int i = 0; i < bullets.size(); i++) {
    Bullet b = (Bullet) bullets.get(i);
    Graphics g = null;
    g.setColor(Color.YELLOW);
    g.fillRect(b.getX(), b.getY(), 10, 5);
}
}

public ArrayList <Bullet> getBullets() {
    return bullets;
}

public void setBullets(ArrayList<Bullet> bullets) {
    this.bullets = bullets;
}

游戏类别:

ArrayList bullets = Player.getBullets();
        for (int i = 0; i < bullets.size(); i++) {
            Bullet b = (Bullet) bullets.get(i);
            if (b.isVisible() == true) {
                b.update();
            } else {
                bullets.remove(i);
            }
        }

玩家等级:

private static ArrayList<Bullet> bullets = new ArrayList<Bullet>();

public void shoot() {
    int centerX = 0; 
    int centerY = 0;
    Bullet b = new Bullet(centerX + 50, centerY - 25);
    Bullet.add(b);
}
public static ArrayList getBullets() {
    return bullets;
}

子弹班:

package game.model;

public class Bullet {

private int x, y, speedX;
private boolean visible;

public Bullet(int startX, int startY){
    x = startX;
    y = startY;
    speedX = 7;
    visible = true;
}

public void update(){
    x += speedX;
    if (x > 800){
        visible = false;
    }

}

public int getX() {
    return x;
}

public int getY() {
    return y;
}

public int getSpeedX() {
    return speedX;
}

public boolean isVisible() {
    return visible;
}

public void setX(int x) {
    this.x = x;
}

public void setY(int y) {
    this.y = y;
}

public void setSpeedX(int speedX) {
    this.speedX = speedX;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

public static void add(Bullet b) {
    // TODO Auto-generated method stub

}

}
评论
  • 回忆那么真
    回忆那么真 回复

    The method Bullet.add(Bullet b) is empty. Make bullets public static and put the following code in add(Bullet b):

    Player.bullets.add(b);