Java 2D游戏朝不同方向拍摄

时间:2017-02-09 20:34:35

标签: java 2d-games 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));
    }
}

射击课:

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);
    }
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以为子弹创建特定方向,而不是访问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;
    }
}