Why to Normalize movement in game dev
After some time in game dev, I found that using Normalize() or normalized was really necessary, but I didn’t understand why. Here a brief explanation.
Requirements:
You need to know what is:
- Vector
- Magnitude
- Pythagoras theorem
Movement in game dev
Let’s analyze a 2D movement
When the player presses the up button, the object moves 2 units upwards (A), and for the right button (B), also it moves 2 units to the right (it’s an example). Both A and B are vectors.
But what happens when the objects moves in diagonal (X)?
X is the magnitude, and it’s calculated through the Pythagoras theorem.
The value of X in this case is 2.8
In that case, we can deduce, understand, that the object will be faster when moving in diagonal.
If a multiplier is applied, the values increase scalarly.
The solution: normalized
The objective of Normalize() or normalized is to set X = 1
How?
Dividing each variable by the magnitude (X)
If you apply the Pythagoras theorem here, you’ll find this
Why?
After “Normalizing” the user input when moving diagonally, the movement value (magnitude: X vector value) will be 1 by reducing the vector values of A and B.
It also applies for 3D vectors — Vector 3
But when pressing only the up or right button, the movement value of each vector A or B will be 1.
So, after using Normalize() or normalized, you can apply a multiplier to the movement input.
Example
Vector3 direction = (player.position — enemy.position).normalized;
Vector3 playerPos = (player.position + direction) * speed;