9
$\begingroup$

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

$\endgroup$
  • $\begingroup$ What do you mesn by " ..point rotating towards the mouse .. " ? Can you add details and elaborate ? $\endgroup$ – Srinivas K Mar 22 '15 at 18:11
  • $\begingroup$ @SrinivasK You know in video games; lets say a top down 2-D tank game. You can control the rotation of the turret, depending on your mouses position. I want to know what formula is used to calculate the angle between the point that's being rotated on, and the point where the mouses position it. $\endgroup$ – Moynzy Mar 22 '15 at 18:14
25
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Clear explanation, ticked answer for diagram and the other solution provided. $\endgroup$ – Moynzy Mar 22 '15 at 18:32
  • 2
    $\begingroup$ Note that the atan2 function usually takes y as 1st argument and x as second argument. $\endgroup$ – user276648 Aug 19 '16 at 9:08

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.