Java游戏旋转图像和轴

时间:2014-09-26 21:24:33

标签: java image-rotation affinetransform

我用宇宙飞船制作了一个游戏,但我有移动它的问题。 这是剧本:

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 而不是对角线

1 个答案:

答案 0 :(得分:1)

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