我正在尝试在游戏中制作一个移动系统,玩家总是朝着某个方向前进,他们可以通过按左右键来改变。到目前为止,我有以下代码:
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);
}
}
此代码适用于运动,但图像不会像我希望的那样旋转以反映方向的变化。如何使图像旋转,以便通常顶部始终指向"方向"(以度为单位的角度(?
您需要仿射变换来旋转图像:
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);
}
}