Search code examples
java2d-gamesdirections

Java 2D Game Shooting in different directions


I am making a simple 2D Game with a player that moves in all directions and shoots.

I managed to make it work so far but there is one problem. When I shoot I want the bullet to go in the direction I am moving. So far I can shoot but when I change the direction of movement of the player the direction of the bullets changes as well.

Can you help me so i can make it that the bullets don't change direction when I am moving around?

Here is a snippet of the movement of the player:

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

And the shooting 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);
    }
}

Solution

  • Instead of accessing to Game.direction you can create a specific direction for the bullet.

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

    then

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