Reputation: 6127
I'm not very good at math( and i never was ) and I've a problem: I'm trying to make sprite always rotated to mouse cursor. That's what i have:
// mx is mouse X and my is mouse y
double rotate = (atan2(my, mx) * PI);
// Set rotation takes rotation in degrees
ship.SetRotation( rad2deg(rotate) );
Where deg2rad
function is:
double rad2deg(double rad)
{
double deg = 0;
deg = rad * (180/M_PI);
return deg;
}
Unfortunately it is not working. The ship is rotating very weird ( really hard to define that ). And I don't have any idea to solve this problem.
I'm working on SFML and SetRotation
takes degrees.
Thanks in advance.
Upvotes: 0
Views: 4152
Reputation: 213200
You need to define the rotation relative to some point. Currently you're doing it relative to the corner of the screen, which will only give you 90 degrees and is probably not what you want. You probably want rotation relative to the sprite's location or perhaps relative to the centre of the screen, e.g.
// define centre of screen
const int Y0 = SCREEN_HEIGHT / 2;
const int X0 = SCREEN_WIDTH / 2;
// get rotation angle of mouse location relative to centre of screen
double rotate = (float) (atan2(Y0 - my), ((mx - X0));
[As others have noted, e.g. @duffymo, you may also have the arguments to atan2 transposed, so I've made this change also.]
Upvotes: 5
Reputation: 309008
I wonder if you have the arguments to atan2 reversed. The typical order is y first, then x. Are you sure you know what you're passing to that method?
"not working" and "weird" don't help us understand what the problem is, so it's hard to help you.
Upvotes: 2
Reputation: 13471
It seems you have wrong argument order for atan2. And also the values you pass to atan2
should be relative mouse position to the object. So if object position is ox
, oy
, then you should use atan2(my-oy, mx-ox)
.
Upvotes: 3