[英]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));
}
}
和射擊課:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.