Math in Unity : Dot Product (Part III)

Matteo Lo Piccolo
3 min readOct 25, 2021

--

Now we will implement our formula to calculate the angle between our Player and the Enemy.

Before doing so, however, we need to clear up one very important thing.

As mentioned earlier, this type of calculation is very useful when we need to rotate a GameObject towards another, or rather we want the FORWARD of a GameObject to rotate in the right direction.

When we work in 3D, often our forward is the Z axis.
But right now we are working on 2D, this means that our forward will be the Y axis.

Obviously it is not a rule, it always depends a lot on what we want to do.

So, if being in 2D, what we want to calculate is the angle between our forward and the enemy’s position with respect to us, in this case the direction.

Now, let’s do a quick test with a Debug.Log()
In Start we create the variable angle and write:

As we can see from the script, we use the Angle() formula created above, passing as parameters our Forward and as the second parameter the distance between us and the enemy.
And since the result will be in RADIANS, we apply the formula
* 180 / MathF.PI
to get the result in DEGREES.
Then a simple Debug.log() to see if our formula works correctly

Reference to MathF.PI
https://docs.unity3d.com/ScriptReference/Mathf.PI.html

It simply returns the value of PI

If we test it now

In this case, the angle is less than 90 °, but if we move the enemy behind our “VIEW”.

The angle will be greater than 90 °.

NOTE : To better understand the angle value, try to imagine our scene divided into 4 quadrants:

the first quadrant starts at Vector3.Up and ends at Vector3.Right,
the second quadrant goes from Vector3.Right to Vector3.Down,
the third goes from Vector3.Down to Vector3.Left,
the last closes the “circle”, from Vector3.Left and returns to Vector3.Up

In practice we have four sections:
top right,
bottom right,
bottom left
top left

If we do some simple tests, we can see that
when the enemy is in the upper right quadrant,
the angle will be between 0 ° and 90 °
exactly like when it will be in the upper left.

If instead we start from what we could define “sides” of the Player,
the range will go from 90 ° up to 180 °,
when the enemy is perfectly behind us.

Hope this clears up some doubts.

In the next article we will use these calculations to rotate our Player in the direction of the enemy!

--

--

Matteo Lo Piccolo
Matteo Lo Piccolo

Written by Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!

No responses yet