15

I'm working on a dial that rotates around a circle.

before click

This dial should lets you mousemove anywhere in a circle to adjust the position of the dial to a point on the circle with the same angle as the click. For example, from the dial above if you clicked the spot shown in pink below I'd move the dial above that point but on the circle.

after click (pink)

I know how to get the position of a point on a circle given a radius and an angle (in radians). That's this formula:

x = Cos(angle) * radius + CenterX;
y = Sin(angle) * radius + CenterY;

However, I am looking to do somewhat of the opposite -- I've got a click point, which I want to turn into a point on a circle (where the control knob goes). I'm trying to use this point (and a given radius) to figure out the angle in radians for it, so that I can place the control knob on the circle at the same angle.

Is there a handy formula I can use to accomplish this?

editor
  • 253
  • 1
  • 2
  • 6

3 Answers3

25

Check out the atan2 function.

It gives you the angle between (0, 0) and (x, y), x and y being the function arguments.

Edit: if the center of the circle isn't (0, 0), no matter, just do this: atan2(y - cy, x - cx).

jcora
  • 7,877
  • 4
  • 49
  • 84
8

You need the center of the knob and the point of the cursor along with the atan2 function. You then use it like this:

 angle = atan2(mouseY - knobCenterY, mouseX - knobCenterX)
William
  • 2,724
  • 1
  • 22
  • 24
5
Point clickPoint;
float angle = Math.atan2(clickPoint.Y - CenterY, clickPoint.X - CenterX);

An ok reference: http://www.mathsisfun.com/polar-cartesian-coordinates.html

Luis Estrada
  • 1,612
  • 1
  • 11
  • 14