[Math] Finding the angle between two points

trigonometry

First of all, I am doing some mathematical background information for a software I am creating.

What I want to achieve is the point on an object rotating towards where the mouse is. Like in tank games, where the turret rotated depending on mouseX and mouseY

In terms of programming, this can be achieved by using the atan2 function, that returns an angle between two points (I believe).

What I want to do is find the angle between an object, and mouse click.
Example

Is there a special maths formula for this? Because my research on google, brings 'atan2' since I'm a programmer. Since most languages have their own maths library, it is abstraction. I want to know how the formula works, in terms of maths.

The question is, what is the formula called for this; to find the angle between two points. So my object can rotate towards the mouseX and mouseY position

Best Answer

The atan2 function is an extended version of the trigonometric inverse tangent function. In the figure below, $\tan{\theta}=y/x$, so $\tan^{-1}{y/x}=\theta$. The atan2 function just calculates $\tan^{-1}{y/x}$ with y and x as separate parameters. The reason it does so is to give a more accurate answer: since the tangent function is periodic, there are multiple values of x and y that would appear to have the same angle (but do not). Also, atan2 provides the correct values when y/x is undefined, such as at $\pi/2$.

atan2 diagram

Another way to find the angle you're looking for is to use vectors. Using the x-axis as one of the vectors and $\vec{OP}$ as another one, you could use the formula

$$\cos{\theta}=\frac{u\cdot v}{||u||\times||v||}$$

Note that whichever way you use, you need two lines to measure an angle. You would have to choose a reference line to measure the angle $\theta$ with; most commonly one would use the x-axis.