有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;

公共静态仿射转换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) 个答案

  1. # 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));       
    }