Unity normalize

Why normalize a vector in Unity ?

Before answering this question, we will see what a normalized vector is.
In Unity and the mathematical world, a normalized vector is a vector with a length of 1.

In Unity, the length is called the magnitude: the following formula represents it “√(x² + y² + z²)”.

Why use a normalized Vector?

Nothing beats an example to illustrate.

We can associate an upward movement with the Vector2(1, 0).
Following the same logic, a diagonal movement (top right) will have the vector Vector2(1, 1).
However, keeping this principle, the character will move much faster with a diagonal movement with his higher magnitude (≈1.414 instead of 1).

To avoid this problem, we will normalize our vector just before the move.
And then our character will move at the same speed, diagonally or not.

How do you use normalize on Unity?

There are two ways to normalize a vector on Unity.

Firstly, we can normalize using the Normalize method, which transforms the current vector into a normalized vector:

private void Update()
{
	var destination = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"));

	// destination is normalized
	destination.Normalize();

	transform.Translate(destination * Time.deltaTime);
}

The second method is to use the normalized property.

The difference in this case is that the property returns the normalized vector without affecting the vector calling the function.

private void Update()
{
	var destination = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"));

	transform.Translate(destination.normalized * Time.deltaTime);
	
	// destination is not normalized
}

Depending on the situation, you may decide to use one or the other.
The use will depend on whether or not you need the normalized vector for other calculations.

For more information on movement in Unity, please see Unity movetowards.

Leave a Reply

Your email address will not be published. Required fields are marked *