2014-09-26 49 views
0

我用飛船做了遊戲,但移動它的時候遇到了問題。 這是腳本:Java遊戲旋轉圖像和座標軸

public class spaceship { 

private final local_client local_client; 

private final int startX; 
private final int startY; 
private final int startR; 

private double x,y,r; 
public static double rotation; 
public static double velo; 

public static AffineTransform at;

public spaceship(local_client local_client,int startX,int startY,int startR) { 
    this.local_client = local_client; 
    this.startX = startX; 
    this.startY = startY; 
    this.startR = startR; 
    x=200; 
    y=200; 
    r=90; 
} 

public void drawImage(Graphics2D g2d) { 
    g2d.drawImage(local_client.spaceship_img,200,200, local_client.game); 
    at = g2d.getTransform(); 

       at.translate(x , y); 
         at.rotate(Math.toRadians(r)); 
      at.translate(-(local_client.spaceship_img.getWidth()/2),-(local_client.spaceship_img.getHeight()/2)); 
    System.out.println(at.getTranslateX() + " - " + at.getTranslateY()); 
       g2d.setTransform(at); 
    g2d.drawImage(local_client.spaceship_img,0,0, local_client.game); 

} 

所以用這個劇本我可以旋轉圖像(見屏幕): http://gyazo.com/c982b17afbba8cdc65e7786bd1cbea47

我的問題是,如果我增加在垂直軸X或Y移動(屏幕): http://gyazo.com/1fb2efb5aff9e95c56e7dddb6a30df4a 和不是在對角線

回答

0

at.translate(x , y);

這行代碼移動你的船周圍,是否正確?增加x和y只會根據軸向上和向下移動它們。

如果您想沿着船的路徑移動,您將不得不使用三角函數來計算實際的x和y來移動。

以下是大概的僞代碼,應該讓你朝正確的方向。取決於你的r,可能會不準確或不準確。

//drive along the ship's nose line 
void moveAlongShipAxis(int magnitude) { 
    x += magnitude * Math.cos(Math.toRadians(r)); 
    y += magnitude * Math.sin(Math.toRadians(r));  
} 
//strafe left and right, if you have that, otherwise you can skip this one 
void moveYAlongTransverseAxis(int magnitude) { 
    y += magnitude * Math.cos(Math.toRadians(r)); 
    x += magnitude * Math.sin(Math.toRadians(r));  
} 
+0

嗨,它是什麼大小,當我不得不稱呼這種方法? – 2014-09-28 18:45:04

+0

@terzi_matte假設汽車是汽車。當你按下油門踏板時,它會立即以100kmph的速度行進,還是會逐漸加快到100kmph?通過增加一個數量級,你可以確定船的行進速度。所以在你的遊戲中100的幅度意味着該船以每秒100px的速度飛行。 10的幅度意味着每秒10px。 – Compass 2014-09-28 20:44:18

+0

是的,非常感謝你,我在1小時後瞭解它,但是謝謝,我認爲你已經扭轉了角色和罪惡:) – 2014-09-30 18:45:12