【问题标题】:How to rotate an image in java for a game?如何在java中为游戏旋转图像?
【发布时间】:2017-05-26 12:45:44
【问题描述】:

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

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

此代码适用于移动,但图像不会像我希望的那样旋转以反映方向的变化。如何使图像旋转,以便通常顶部始终指向“方向”(以度为单位的角度)?

【问题讨论】:

  • 你可以维护一个标志来定义玩家指向的方向,然后你可以简单地相应地旋转Graphics上下文
  • 这取决于你如何调用渲染函数。如果你可以把 sn-p 关于热你调用的功能会有所帮助
  • 每秒多次调用render方法来绘制玩家图像,就好像它在移动一样。

标签: java graphics


【解决方案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);
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-09
    • 2011-09-08
    • 2018-02-18
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多