0
\$\begingroup\$

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

So what's wrong? why I get bad results?

\$\endgroup\$
  • \$\begingroup\$ I dont understand, it looks like its working? \$\endgroup\$ – user55564 Dec 8 '14 at 1:29
1
\$\begingroup\$

This may not be the answer but, instead of using

sprite.rotate(float angle); 

use:

sprite.setRotation(float angle); 

Hope this helps! :D

\$\endgroup\$
0
\$\begingroup\$

You are rotating the sprite using an int, 0-360, instead of a float.

Try doing

sprite.setRotation(angle/360f);

\$\endgroup\$
0
\$\begingroup\$
sprite.rotate(float degrees);

and

sprite.setRotation(float degrees);

is different methods, "sprite.rotate" is adding degrees to current "angle", "sprite.setRotation" is set given degrees to the angle.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.