Search code examples
mathrotationdegreesradians

How to convert mouse movements to rotation of an element


I'm building a wheel menu control. The idea is you spin the wheel until the item you want to act on is in view, then you click on it or whatever. I'm trying to figure out how to translate the user's mouse movements (x & y) into the number of degrees to spin the wheel. I can implement it all, I just am missing the math to do the conversion. Any help or pointers are appreciated!


Solution

  • Angle between mouse positions

    If the user moves the mouse from [x1,y1] to [x2,y2], what you basically want is to find

    θ=θ12

    Where:

    θ1 = Math.atan2(y1, x1);

    θ2 = Math.atan2(y2, x2);

    Now all of this depends on where you define your origin (center of your wheel). If your origin is [x0,y0], then just subtract those values from the actual mouse co-ordinates.

    Also on screen, the co-ordinate system is upside down, so 0,0 is in the top-left instead of bottom-left, so you'd need to flip that, but the math is essentially the same.

    Also note that the angle is measured in radians and not degrees.