I wan't my sprite to point at the cursor, how do I compute on how much do I need to rotate it?
//First is get the cursor position
x=Gdx.input.getX();
y=Gdx.input.getY();
//then rotate the sprite and make it point where the cursor is
Sprite.rotate(??);
update--> I tried this but I don't know what should be the condition to make it stop rotating when is already pointed at the right direction
double radians = Math.atan2(mouseY - spriteY, mouseX - spriteX)
float fl=(float)radians;
Sprite.rotate(fl)
update 2--> It barely moves when I do this:
public void update(){
int x=Gdx.input.getX();
int y=Gdx.input.getY();
double radians=Math.atan2(y-Spr.getY(),x-Spr.getX());
float angle=(float)radians;
Spr.setRotation(angle);
}
update 3 --> So now I think it's following the cursor but it uses the opposite part of the sprite, Imagine an arrow instead of pointing using the pointy part of the arrow it uses the opposite side of the arrow, hope you understand what I mean, btw this is what I did instead:
public void update(){
int x=Gdx.input.getX();
int y=Gdx.graphics.getHeight()-Gdx.input.getY();
double radians= Math.atan2(y - launcherSpr.getY(), x - launcherSpr.getX());
float angle=(float)radians*MathUtils.radiansToDegrees; //here
launcherSpr.setRotation(angle);
}
You can use
Math.atan2(double y, double x)
for the desired effect.This method computes the angle in polar coordinates assuming that you have a point at
(0,0)
and another at a given(xo,yo)
. So to make it work you must normalize the values so that the origin point is the position of the sprite and the(xo,yo)
is the relative position of the mouse compared.Basically this reduces to:
Try with
sprite.setRotation(float angle);
if you want to fit your sprite to a certain rotation.EDIT
I don't know if
rotate()
adds a rotation to the actual so, if this the case, your object will rotate everytime you call this method. Try usesetRotation()
, but remember that works with degrees, and some methods, likeMathUtils.atan2()
returns a radian value, so you have to convert that result to degree.I guess there's a function like
MathUtils.toDegrees()
orMathUtils.radiansToDegrees()
that can help you for that purpose.EDIT 2
Another problem that could be happening is that
input.getY()
is inverted so (0,0) is at the top left.The correct way should be something like this: