Tuesday, June 23, 2015

mathematics - What are atan and atan2 used for in games?


I am having some trouble understanding Math.tan() and Math.atan() and Math.atan2().


I have basic knowledge of trigonmetry but the usage of SIN, COS, and TAN etc for game development is very new to me.


I am reading on some tutorials and I see that by using tangent we can get the angle in which one object needs to be rotated by how much to face another object for example my mouse. So why do we still need to use atan or atan2?



Answer




The tangent formula is this:


tan(angle) = opposite/adjacent


Refer to this drawing:


Diagram of a right-angled triangle, with an angle theta and its opposite and adjacent sides marked


Where a is the adjacent side, o is the opposite side and theta is the angle. Similarly, sine and cosine are sin(ang)=o/h and cos(ang)=a/h where h is the long side: http://www.mathwords.com/s/sohcahtoa.htm


Meanwhile atan (short for arc-tangent, also known as the inverse tangent) is the reverse of tan, like so:


atan(opposite/adjacent) = angle


Thus, if you know the values of both the opposite and adjacent sides (for example, by subtracting the object's coordinates from the mouse coordinates) you can get the value of the angle with atan.


In game development though, it can happen fairly often that the adjacent side is equal to 0 (e.g. the x coordinate of a vector being 0). Remembering that tan(angle) = opposite/adjacent the potential for a disastrous divide-by-zero error should be clear. So a lot of libraries offer a function called atan2, which lets you specify both the x and y parameters, to avoid the division by zero for you and give an angle in the right quadrant.


atan2 diagram



(diagram courtesy of gareth, please vote up his answer too)




The use of trigonometry in game development is pretty common, especially with vectors, but usually libraries hide the trigonometry work for you. You can use sin/cos/tan for a lot of tasks which involve geometric manipulations to find a value from a triangle. All you need is 3 values (side lengths / angle values) to find the other values of a rectangle triangle, so it's quite useful.


You can even use the "cycling" nature of the sine and cosine functions for special behaviors in a game, e.g. I've seen cos/sin used a lot to make an object turn around an other one.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...