Java 不同方向的 2D 游戏射击

Java 2D Game Shooting in different directions

我正在制作一个简单的 2D 游戏,玩家可以向各个方向移动并射击。

到目前为止我设法让它工作,但有一个问题。当我射击时,我希望子弹朝我移动的方向移动。到目前为止我可以射击但是当我改变玩家的移动方向时子弹的方向也会改变。

你能帮我一下,让我在移动时子弹不会改变方向吗?

以下是球员动作的片段:

public static int direction;

public void keyPressed(KeyEvent k) {
    int key = k.getKeyCode();

    if (key == KeyEvent.VK_RIGHT) {
        player.setVelX(5);
        direction = 1;
    } else if (key == KeyEvent.VK_LEFT) {
        player.setVelX(-5);
        direction = 2;
    } else if (key == KeyEvent.VK_DOWN) {
        player.setVelY(5);
        direction = 3;
    } else if (key == KeyEvent.VK_UP) {
        player.setVelY(-5);
        direction = 4;
    } else if (key == KeyEvent.VK_SPACE) {
        controller.addFire(new Fire(player.getX(), player.getY(), this));
    }
}

还有射击class:

public class Fire {

    private double x,y;
    BufferedImage image;

    public Fire(double x, double y, Game game){
        this.x = x;
        this.y = y;
    }
    public void tick(){

        switch (Game.direction){
            case 1:
                x += 10;
                break;
            case 2:
                x -= 10;
                break;
            case 3:
                y += 10;
                break;
            case 4:
                y -= 10;
                break;
        }
    }
    public void render(Graphics graphics){
        graphics.drawImage(image, (int)x, (int)y, null);
    }
}

我认为您需要做的是在您的 Fire 构造函数中检查 Game.direction,然后立即设置子弹速度(为其创建一个私有变量)。这样,如果 Game.direction 以后发生变化,该变化将不会影响项目符号。

您可以为子弹创建一个特定的方向,而不是访问 Game.direction

new Fire(player.getX(), player.getY(), direction)

然后

public Fire(double x, double y, int direction){
    this.x = x;
    this.y = y;
    this.direction = direction;
}

public void tick(){

    switch (direction){
        case 1:
            x += 10;
            break;
        case 2:
            x -= 10;
            break;
        case 3:
            y += 10;
            break;
        case 4:
            y -= 10;
            break;
    }
}