c++cgeometrysdltrigonometry

How do you rotate a sprite based on mouse position?


Basically, I have a sprite that I render using SDL 2.0 that I can rotate a variable amount around a center orgin point of the texture clockwise using SDL_RenderCopyEx(). I want to rotate it based on the mouse position by using the angle x between my physical slope line and my two straight lines based off of my base line. The base line I'm talking about can be represented mathematically as x = orgin_x, where orgin_x is the rotation orgin. The other line is a segment along the baseline that connects the horizontal line end point to the orgin_x point vertically. With the angle to the mouse cursor being the one I want to find to rotate my character.

Please no complicated math symbols. I would rather the formula be posted in C-style format, and please explain the logic behind the math so I can maybe understand what's happening and fix similar future problems if needed.


Solution

  • Some basic trigonometry. You can use atan2(delta_y, delta_x). With this you will get your angle in RAD. To get your angle in degree, because RenderCopyEx use Degree for angle, you need to convert your angle. You got 360 Degree and 2*PI Rad for a full circle. So

    angle_deg = (atan2(delta_y, delta_x)*180.0000)/3.1416

    Now you got your angle to do a RenderCopyEx

    BTW :

    delta_y = origin_y - mouse_y

    AND

    delta_x = origin_x - mouse_x