-
Notifications
You must be signed in to change notification settings - Fork 8
Normalization
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()
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)