Normalization - leiget/Godot_FPC_Base GitHub Wiki
Normalization is simple: it changes the magnitude (length) of a vector to 1.0. This is so it can be used in any way you want by just multiplying, manipulating, or comparing the vector against other vectors or scalers.
It goes like this: letβs say we have a 2D vector called β2D_Vector_01β that is β(2.5, 7.5)β.
But we want to dot product this vector to another one called β2D_Vector_02β that is β(0.5, 0.1)β. How do we do this? If we didnβt normalize both of these vectors, the result of a dot product between them would be β2.0β. This is not what we need.
So what we do is normalize both vectors. We do that in Godot by simply by calling βnormalized()β from the vector we want to normalize. Example:
2D_Vector_01 = 2D_Vector_01.normalized()
Pythagorean Theorem
But what is going on behind the scenes? Itβs simple. Letβs take our first vector of β(2.5, 7.5)β. We need to get the magnitude (length) of the vector. So we use the Pythagorean theorem to get it. It goes like this:
magnitude = β(x^2 + y^2)
Which in this case would be:
magnitude = β(2.5^2 + 7.5^2) = β(6.25 + 56.25) = β62.5 = 7.90569415
The variables βxβ and βyβ always need to be positive numbers.
The Pythagorean theorem actually just looks like this:
a^2 + b^2 = c^2
If βaβ, βbβ, and βcβ were the lengths of the three sides of a triangle. But in order to get the length of a vector, we do just as we have done in the previous code snippets. I just wanted to let you know what the Pythagorean theorem actually was.
We could of also used βVector01.length()β to get the magnitude of the vector, but we wouldnβt of learned as much.
Anyway, we now know how long the vector is. But what we want is for it to be β1.0β. We get this by simply taking each element of the vector and divide them by the magnitude, like this:
normalized_vector = (2.5 / 7.90569415 , 7.5 / 7.90569415) = (0.316227766 , 0.948683298)
So now our normalized vector is β(0.316227766 , 0.948683298)β. And if we were to get the length of that vector it would simply be β1.0β. Awesome.
If we normalized β2D_Vector_02β (that is β(0.5, 0.1)β), it would be β(0.980581, 0.196116)β. Now we can dot product these two vectors, which would equal β0.496139β, which is what we want. If we wanted to we could get the angle between these two vectors by using the following code:
angle = rad2deg( acos( 2D_Vector_01.dot(2D_Vector_02) ) ) = ~60.255 degrees
Not letβs look at a new example. Letβs say that the length of a vector was something like this:
This is already normalized, right? Because the vectorβs coordinates are in the range of 0.0 to 1.0? No, it isnβt normalized because the length of the vector is not 1. What is the length of the vector? Letβs find out:
magnitude = β(0.842 + 0.862) = 1.202164714
So the length of our vector is actually β1.2β... Well, then, letβs make it β1.0β:
normalized_vector = (0.84 / 1.202~ , 0.86 / 1.202~) = (0.698739524 , 0.715376179)