Math in Unity - Calculating Angles
Angles are used quite often in video games. We talked about rotation before, and angles are a perfect combination here! As you change your direction, you might have another angle to the GameObject looking at you. To keep track of you, it needs to calculate the angle it has to look at you. Let’s take on how to implement this behavior today!
I. What the objective?
The objective is to let the Capsule “point” towards the player cube.
II. The mathematical aspect
We need some math functions to calculate the angle. We already have two sides given on the triangle. The value on the hypotenuse is missing and needs to be calculated. For that, tan will come in handy, as the formula is the length of the opposite divided by the length of the adjacent, or Opp/Adj for short.
The tan method will return a value, but no angle. To convert the value into an angle, we need to perform the inverse tangents math function.
Let’s create a quick example:
The opposite is 4, the adjacent is 3
→ 4/3 = 1.25
To get the angle, use the inverse tangents function
→ tan^-1(1.25) = 51.34
The angle we need is 51.34°.
Now let’s implement the calculation through code!
III. Implementing the calculation
Let’s write down what we want to do first.
To be able to calculate a direction, we need to assign a reference to the enemy as well.
We already discussed how to calculate the direction in yesterdays article. To calculate the angle, we use Mathf.Atan2(). Atan2 because it will convert negative values into positive ones. Atan will not allow any negative values. As we want to convert the tan value into degrees, we need to convert it with Mathf.Rad2Deg.
The last thing to do is to actually rotate the GameObject. To do that, we will manipulate the Euler angles.
Running this in Unity will bring back something odd. The calculated angle seems to be right, however, the Capsule does not point to the player cube.
The direction arrows on the capsule are helpful here! The capsule rotated 90° too far! That’s an issue exclusive to Unity because Unity’s Unit Circle is different than the one you know from Maths. To fix that, we simply need to offset the calculated angle by 90°.
IV. The working end result
Having done all that, let’s take a look at the end result:
No matter where the cube wants to be, he will always be tracked by the capsule now.
Oh, and as always, here’s the complete code:
Another newly discovered thing which surely can be really helpful! It’s pretty exciting how math can be so interesting. Just wish Maths in school would have been so interesting…
Anyways, thank you for your time and interest to read the article!
See you around next time!