2
$\begingroup$

enter image description here

I'm trying to convert an analog stick from a game controller into degrees. It gives me a range from $-1$ to $+1$ on the $x$ and $y$ axes. I can get values for $x$ and $y$. If dead right is $0$ degrees how can I find the angle of the red dot in degrees?

$\endgroup$
4
$\begingroup$

Look at the atan2 function of your favourite programming language. It will compute an expression such as $\arctan(\frac yx)$ for the first quadrant etc. Also note that the point you drew up has coordinates $-\frac1{\sqrt2}, \frac1{\sqrt2}$ and not $-1,1$, since it's on the unit circle. The corresponding angle will be $\frac{3\pi}4$ in this case.

Per @robjohn's answer, you can also use $2\arctan(\frac y{1+x})$ for $(x,y) \ne (-1,0)$ on the unit circle.

$\endgroup$
  • $\begingroup$ I chose your answer because of your direction to atan2. I overcame the -1 problem by adding 360 to the result if it is < 0. $\endgroup$ – bwoogie Aug 17 '15 at 21:31
  • 1
    $\begingroup$ @bwoogie That's okay as long as atan2 spits out your angle in degrees. Otherwise you must add $2\pi$ or convert to degrees with the factor $\frac{180}\pi$. $\endgroup$ – AlexR Aug 17 '15 at 21:33
  • $\begingroup$ It does! It can also give radians if desired. $\endgroup$ – bwoogie Aug 17 '15 at 21:35
2
$\begingroup$

Using the arctan function usually needs one to adjust quadrants if $x\lt0$. However, one can use $$ \theta=2\arctan\left(\frac y{r+x}\right) $$ where $r=\sqrt{x^2+y^2}$, to get the angle without quadrant adjustments (unless $x\le0$ and $y=0$, in which case $\theta=\pi$ works).

$\endgroup$
  • $\begingroup$ N.B. In programming, most languages are equipped with a function called atan2, which avoids the divide-by-zero error you might identify above. (Oh, I see now another answer has covered that.) $\endgroup$ – Emily Aug 17 '15 at 20:58
  • 1
    $\begingroup$ @Arkamis: yes. I added a bit about the division by $0$ when $x\le0$ and $y=0$. However, in most cases, this works better than $\arctan\left(\frac yx\right)$. $\endgroup$ – robjohn Aug 17 '15 at 21:02
  • $\begingroup$ Small addition to the atan2 remark: Convergence of the base algorithm behind this function is much better than that of $\arctan$ since it uses a specialized iterative approach. $\endgroup$ – AlexR Aug 17 '15 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.