Google says trigonometry is:
“the branch of mathematics dealing with the relations of the sides and angles of triangles and with the relevant functions of any angles,” which might sound a little boring at first, but let’s break that down a bit.
Two of the most primitive forms of AI (Artificial Intelligence) are Turrets (any stationary object that shoots at another object) and Chasing.
For both, identifying the angle to the target is the first goal. If I take the target’s (X, Y) coordinate and subtract the Enemy’s (X, Y) coordinate, I’m going to get the difference in their positions.
This is often referred to as the “delta” (Greek symbol for Change), which uses the symbol Δ. The X and Y components of Δ are referred to as Δx and Δy respectively.
In geometry, we learn about SohCahToa (Sine = Opposite/Hypotenuse, Cosine = Adjacent/Hypotenuse, Tangent = Opposite/Adjacent). Our Enemy and Target forms a triangle with Δx being the horizontal (adjacent) segment.
Since we need to find the angle, we know that the tangent is Δy/Δx, and if we take the inverse of that tan (on your calculator this might be atan or tan-1) it will give us the correct angle to fire or chase.
Firing a bullet or running at that angle will give us the correct direction. In practice, a game programmer would use the vector directly. This also gives us the direction the enemy, turret and how the projectile should face as it’s moving.
Having a college-level understanding of trigonometry, geometry and calculus is not only encouraged but a requirement for all game designers and programmers. Consider taking a class to brush up on these areas of mathematics to make sure you are ready to learn video game design or programming at the college level.
The Pythagorem Theorem
Lastly, how far do we need to travel? The Pythagorean Theorem is incredibly useful here (a2 + b2 = c2), but in the video game world we usually think of it in terms of the total distance (D) using Δ – so we re-write the equation to look more like
D = √(Δx2 + Δy2)
This is used in the same equation, but the format makes it a little easier for us. We don’t have to think about what a, b and c represent, and it’s also easier to integrate into code for your game.