繁体   English   中英

如何在Java中旋转游戏图像?

[英]How to rotate an image in java for a game?

我正在尝试制作一种游戏系统,在该系统中,玩家始终朝着某个方向前进,通过按左右键可以改变方向。 到目前为止,我有以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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