David
David

Reputation: 3105

Sprite rotation is not working fine LibGDX

I'am using the current mouse position to aim the player sprite, but I am not getting the best results. I want my sprite to have the direction pointed wherever my cursor is in the screen. Here's the result I want to get. (When I move my mouse jet rotates slowly)enter image description here

But this is what I get: 1) when my mouse position y = 0 jet sprite rotates very slowly (BUT ROTATION NEVER STOPS)

enter image description here

2) When my y = (Screen Height) sprite rotates VERY FAST (and it also never stops) enter image description here Here's my code: My update method

public void update(float dt){
    time += dt;
    float yInput = (Gdx.graphics.getHeight() - Gdx.input.getY());
    vec.set(Gdx.input.getX() - position.x, yInput - position.y).nor();
    //position is a Vector2 update sprite coordinates 
    position.x += vec.x * 15f;
    position.y += vec.y * 15f;
}

and here's my draw method

public void draw(){
    batch.begin();
    sprite.setPosition(position.x - sprite.getWidth()/2, position.y - sprite.getHeight()/2);

    float xInput = Gdx.input.getX();
    float yInput = (Gdx.graphics.getHeight() - Gdx.input.getY());

    float angle = MathUtils.radiansToDegrees * MathUtils.atan2(yInput - position.y, xInput - position.x);

    if(angle < 0){
        angle += 360;
    }
    sprite.rotate(angle);

    sprite.draw(batch);
    batch.end();
}

Upvotes: 2

Views: 2318

Answers (1)

MadEqua
MadEqua

Reputation: 1142

In your draw method, replace sprite.rotate(angle); with sprite.setRotation(angle);.

rotate() will rotate the sprite relative to the current rotation. atan2 returns an absolute angle and that may be causing your problem.

Upvotes: 2

Related Questions