简体   繁体   中英

Java game rotate image and axis

i have made a game with a spaceship but i have a problem with moving of it. this is the script:

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

}

So with this script i can rotate image (see the screen): http://gyazo.com/c982b17afbba8cdc65e7786bd1cbea47

My problem is that if i increment X or Y move on the normal axis (screen) : http://gyazo.com/1fb2efb5aff9e95c56e7dddb6a30df4a and not in diagonal

at.translate(x , y);

This line of code moves your ship around, correct? Incrementing x and y will only move them up and down according to the axis.

You will have to use trigonometry like you have with your rotations to calculate the actual x and y to move if you want to move along the ship's path.

The following is the approximate pseudocode that should get you in the right direction. May or may not be accurate depending on your 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));       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM