John
John

Reputation: 11

How to rotate an image in java for a game?

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)?

Upvotes: 1

Views: 563

Answers (1)

AbelSurace
AbelSurace

Reputation: 2273

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

Upvotes: 2

Related Questions