2017-05-26 62 views
0

我想在游戏中制作一个运动系统,玩家总是按照某个方向前进,通过按左右键可以改变他们。到目前为止,我有这样的代码:如何在Java中为游戏旋转图像?

public class Player 
{ 
    private float x, y; 
    private int health; 
    private double direction = 0; 
    private BufferedImage playerTexture; 
    private Game game; 

    public Player(Game game, float x, float y, BufferedImage playerTexture) 
    { 
     this.x = x; 
     this.y = y; 
     this.playerTexture = playerTexture; 
     this.game = game; 
     health = 1; 
    } 

    public void tick() 
    { 
     if(game.getKeyManager().left) 
     { 
      direction++; 
     } 
     if(game.getKeyManager().right) 
     { 
      direction--; 
     } 
     x += Math.sin(Math.toRadians(direction)); 
     y += Math.cos(Math.toRadians(direction)); 
    } 

    public void render(Graphics g) 
    { 
     g.drawImage(playerTexture, (int)x, (int)y, null); 
    } 
} 

此代码工作正常的运动,但图像不旋转,以反映方向的变化,我想它。我怎样才能使图像旋转,以便通常顶部始终指向“方向”(这是一个以度为单位的角度)?

+0

你可以保持它定义了播放器所指向的方向,从您可以简单地accordingnly旋转'Graphics'背景 – MadProgrammer

+0

它的标志取决于ru如何调用渲染函数。如果你可以放热片段你打电话的功能将是有帮助的 –

+0

渲染方法被称为每秒多次绘制播放器图像,如果它正在移动。 – John

回答

1

你需要一个仿射变换,旋转图像:

public class Player 
{ 
private float x, y; 
private int health; 
private double direction = 0; 
private BufferedImage playerTexture; 
private Game game; 

public Player(Game game, float x, float y, BufferedImage playerTexture) 
{ 
    this.x = x; 
    this.y = y; 
    this.playerTexture = playerTexture; 
    this.game = game; 
    health = 1; 
} 

public void tick() 
{ 
    if(game.getKeyManager().left) 
    { 
     direction++; 
    } 
    if(game.getKeyManager().right) 
    { 
     direction--; 
    } 
    x += Math.sin(Math.toRadians(direction)); 
    y += Math.cos(Math.toRadians(direction)); 
} 
AffineTransform at = new AffineTransform(); 
// The angle of the rotation in radians 
double rads = Math.toRadians(direction); 
at.rotate(rads, x, y); 
public void render(Graphics2D g2d) 
{ 
    g2d.setTransform(at); 
    g2d.drawImage(playerTexture, (int)x, (int)y, null); 
} 
}