<- back
notes

atan2
in high school geometry, you were told that the angle between vector $\begin{bmatrix}x\\y\end{bmatrix}$ and the x-axis was $\theta_\text{atan}(y, x) = \tan^{-1}\left(\frac{y}{x}\right)$ however, this is a pretty bad formula in practice consider vector $\begin{bmatrix}1.0\\1.0\end{bmatrix}$; the formula says its angle is $\theta_\text{atan}(1.0, 1.0) = \tan^{-1}\left(\frac{1.0}{1.0}\right) = \tan^{-1}(1.0) = 45\deg$ so...so far so good... except now, consider vector $\begin{bmatrix}-1.0\\-1.0\end{bmatrix}$; it's angle is apparently also $45 \deg$; oh no :( the issue is that $\theta_\text{atan}(y, x)$ only returns angles in the interval $[-90\deg, 90\deg]$; calling it on the vector $\begin{bmatrix}-1.0\\-1.0\end{bmatrix}$ is invalid a better equation might be something like this (i'm leaving out edge cases) $\theta_\text{atan2}(y, x) = \begin{cases} \theta_\text{atan}(y, x) & x > 0\\ \theta_\text{atan}(y, x) + 90 \deg & x < 0, y > 0\\ \theta_\text{atan}(y, x) - 90 \deg & x < 0, y < 0\\ \end{cases}$ now we get angles in the interval $[-180\deg, 180\deg]$; yay! :) PS the order of the arguments is (yet another) source of potential problems therefore if you have a snail vector, and really decide you want its angle, i provide the wrapper real atan2(vec2 v) { return atan2(v.y, v.x); } which you may use like this - given vec2 v; real theta = atan2(v);