← Back to the index page

Arctangent function in Lua

Simple trigonometric function arctangent is very confusing in Lua. In Lua version 5 this function changed many times. I found such variants:

It is very confusing. Let’s try to figure out what is what.

What is the trigonometric arctangent function

Time to remind a school math class.

Calculating and finding angles is a very common task for game developers. Arctagnent allows to find the angle between a point and X-axis with ease.

Figure 01. Arctangent angles with arctangent

We know two points: A(10, 10) and O(0, 0)* is center. If 2 points are known, then we can make a line between them. General equation of a line (linear function):

y = kx + c*

Where:

Consider point A(10, 10):

y = tan(α) * x
tan(k) = y/x
α = arctan(y/x)
α = arctan(10/10) = arctan(1)
α ≈ 0.78539 = 45°

Consider point B(5, -10):

y = tan(α) * x
tan(k) = y/x
α = arctan(y/x)
α = arctan(-10/5) = arctan(-2)
α ≈ -1.107149 ≈ -63.4349°

Lua function

Lua’s built-in math library calculates everything written above for you. But there are many versions in different Lua versions and which to use. Usually math.atan() or math.atan2() functions confuse beginners.

Warning

Function math.atan2() is deprecated and might not work in your environment.

The general rule is to use math.atan() in the form.

local x, y = 10, 10
print(math.atan(y / x)) --> 0.78539816339745 radians which equal 45 degrees

This should work with every Lua version.

Conclusion

Bonus: converting radians to degrees and vice-versa

Function to convert radians to degrees:

local function rad2deg(r)
    return r * (180 / math.pi)
end

Function to convert degrees to radians:

local function deg2rad(d)
    return d * (math.pi / 180)
end

References

Feedback

For feedback, please check the contacts section. Before writing, please specify where you came from and who you are. Sometimes spammers go insane. Thank you in advance for your understanding.

← Back to the index page