1
\$\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\$
1
  • \$\begingroup\$ I dont understand, it looks like its working? \$\endgroup\$
    – user55564
    Dec 8 '14 at 1:29
3
\$\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\$
1
\$\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\$
0
\$\begingroup\$

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

Try doing

sprite.setRotation(angle/360f);

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .