Search code examples
javalibgdx

How do i correctly rotate an image in LibGDX?


I am trying to make a game like asteroids, i want the player to face and move upwards (North) but when the game starts,the player is faceing to the right side(east). here is my code:

public Player(float x, float y,int width,int height) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
}

public void update(float delta) {
    if(up) {
        x += Math.cos(Math.toRadians(rotation)) * Constants.PLAYER_SPEED * delta;
        y += Math.sin(Math.toRadians(rotation)) * Constants.PLAYER_SPEED * delta;
    }else if(right){
        rotation -= Constants.PLAYER_ROTATION * delta;
    }else if(left){
        rotation += Constants.PLAYER_ROTATION * delta;
    }
    wraparound();
}

Then i draw my player from texture region like this:

batch.draw(playerTR, player.getX(),player.getY(),
            player.getWidth()/2.0f,player.getHeight()/2.0f,
            player.getWidth(),player.getHeight(),1,1,player.getRotation());

please some help me out.


Solution

  • Your rotation variable is by default initialized to 0. Try to initialize it to 90 and your player should start facing North:

    public Player(float x, float y,int width,int height) {
        ...
        rotation = 90.0f;
    }
    

    The rest of your code seems OK to handle it.