Why is diagonal movement 1.4x faster in Unity?

In by John FrenchPublished Updated

When moving an object using horizontal and vertical axes it’s possible to create diagonal movement that is faster than the speed of movement of a single axis. This is because the length of the vector that’s created from a forward vector of 1 and a sideways vector of 1 is longer than either one on their own, at around 1.4.

Which means that holding forward and right on a keyboard, for example, would move the player 1.4 times faster than just moving forwards or sideways alone, causing uneven 8-way movement.

One method for fixing this is to limit the length of the vector, using Clamp Magnitude.

Like this:

public float speed = 2;

void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(x, 0, z);
    movement = Vector3.ClampMagnitude(movement, 1);

    transform.Translate(movement * speed * Time.deltaTime);
}

This will limit the length of the vector to one, while leaving lower values intact, allowing you to create analogue 8-way movement that’s even in all directions.

See also: