2017-02-09 54 views
1

我正在製作一個簡單的2D遊戲,玩家可以在各個方向移動並拍攝。Java 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); 
    } 
} 

回答

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

謝謝!這工作得很好。乾杯! –

+0

我很高興聽到這個消息。如果我幫你,接受這個答案。 – enucar

3

我認爲你需要做的是檢查Game.direction在你的火焰構造什麼,然後設置子彈速度(爲其創建一個私有變量)。這樣,如果Game.direction稍後發生更改,則該更改不會影響子彈。

+0

這聽起來我的權利。他使用'Game.direction'作爲所有單獨項目符號引用的全局變量,但每個項目符號都需要「記住」其初始速度,以便它在其生命週期中以一致的方向移動。 – DavidS