Math in Unity : Dot Product (Part II)
The time has come to put the “theory” into practice.
We will continue to work on the same project as our sprite.
First, we’ll create a method for the DotProduct(), then apply the second formula from the previous article to create a method for calculating the angle.
In the SpriteMove script these will be our two methods:
In both methods we pass the two Vectors as parameters.
I have called the two variables v and w to stay consistent with the formulas, so that it may be clearer what we will do.
Let’s start with the Dot Product. If you remember the formula to calculate it is
vx * wx + vy * wy
So we apply exactly the same formula in our method:
we will take the x of v and we will multiply it by the x of w, same thing with the y, so vy * wy, and we will add them.
This is the final result.
So far everything simple.
To make everything even more similar to the formula we could write like this:
One line of code.
Small note: obviously these formulas work in both 2D and 3D, the only difference is that the z axis should be added to the calculation.
((v.x * w.x) + (v.y * w.y) + (v.z * w.z));
To make less confusion, however, I will change the parameter from Vector2 to Vector3.
I hope this passage is clear.
Now, the angle formula is a little more complicated.
Let’s try to understand:
Angle = inverse cosine of the DotProduct divided by the length of the Vector v multiplied by the length of the Vector w.
It always seems complicated, but it is actually much more “understandable” written this way.
We now have the DotProduct formula.
And also the “Length” formula because the Distance () method returns exactly the Length of a Vector.
What causes confusion probably is
THE INVERSE COSINE.
And this is where the MathF Class comes to our rescue!
Unity reference to MathF
In these situations, MathF is almost always the answer to our math problems.
In this specific case, we need the inverse cosine
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do…
Let’s try to break the formula into two sections:
We start with a float variable, then we write the formula :
we calculate the Dot between the two Vectors v and w.
Next we divide by the length of v and w multiplied by each other.
Now we have a part of the formula, to complete it we need the MathF.Acos method.
To use it, we simply do this:
I hope the meaning is clear, obviously to have a certain fluidity with this type of thing we need practice, but the important thing is always to understand what you want to do and how to apply it.
One last important thing to clarify is that the Acos method returns the angle in RADIANS, not DEGREES.
To convert radians to degrees, we need to multiply the result by 180 / PI.
In the next article we see how to implement it exactly.