I'm trying to make a movement system in a game where the player is always moving forward in a certain direction which they can change by pressing left and right keys. So far I have this code:
我正在尝试在游戏中制作一个移动系统,玩家总是向某个方向前进,他们可以通过按左右键来改变。到目前为止,我有这个代码:
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);
}
}
This code works fine for the movement, but the image does not rotate to reflect the change in direction as I would like it to. How could I make the image rotate so that what is normally the top is always pointing towards "direction" (which is an angle in degrees)?
此代码适用于移动,但图像不会旋转以反映我希望的方向变化。我怎样才能使图像旋转,使通常顶部的图像始终指向“方向”(这是一个以度为单位的角度)?
1 个解决方案
#1
2
You need an affine transform to rotate the image:
您需要仿射变换来旋转图像:
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);
}
}
#1
2
You need an affine transform to rotate the image:
您需要仿射变换来旋转图像:
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);
}
}