java - 如何在java中旋转游戏中的图像?

标签 java graphics

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

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

这段代码对于运动效果很好,但是图像不会像我希望的那样旋转以反射(reflect)方向的变化。我怎样才能使图像旋转,以便通常顶部始终指向“方向”(以度为单位的角度)?

最佳答案

您需要仿射变换来旋转图像:

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

关于java - 如何在java中旋转游戏中的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44192875/

相关文章:

r - 使用 sjPlot 从 glmer 模型中绘制随机斜率

java - 为什么我的 Oracle JVM 会为一个简单的 'Hello World' 程序创建所有这些对象?

java - 如何在单个图像中聚集颜色?

java - 使用线程计算给定数组中完美正方形的数量

Java Thread.stop() 与 Thread.interrupt()

javascript - 哪个 JavaScript 图形库的性能最好?

java - 用空格分隔字符串,但在拆分数组中保留换行符

python - 如何在 PyGame 中绘制到离屏显示

java - 如何用openGL生成Winamp风格的可视化效果? (奶滴等)

javascript - 图形中的蒙特卡洛方法