Menu
CoddyTech

Diagonal Speed

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 20 of 67.

Hold the right and up arrows together and the raw axes give the direction (1, 0, 1). Its length, .magnitude, is the square root of 1 + 1, about 1.41. A walker moved by it covers 1.41 units on a diagonal in the time it covers 1 unit straight ahead: 41% faster.

.normalized gives a copy of a vector that points the same way and is exactly 1 unit long: (1, 0, 1) becomes about (0.71, 0, 0.71), and (0, 0, 5) becomes (0, 0, 1). Times a speed, it moves at that speed whatever the direction. This bee flies toward the flower at 2 units per second whether the flower is far or near; without .normalized it would fly faster the farther away the flower is:

public Vector3 flower = new Vector3(4, 1, 3);
public float speed = 2f;

void Update()
{
    Vector3 toFlower = flower - transform.position;
    transform.position += toFlower.normalized * speed * Time.deltaTime;
}

Vector3.zero.normalized stays (0, 0, 0), since zero has no direction. v.normalized leaves v as it was; v.Normalize() changes v itself.

challenge icon

Challenge

Easy

Write the walker's movement. The arrows (or WASD), read with the raw axes, move it left and right along x and up and down along z. It moves at speed units per second in every direction, diagonals included, starts and stops at once, and stays put with no key held.

Press Play, walk straight and diagonally, then press Check.

Try it yourself

using UnityEngine;

public class Walker : MonoBehaviour
{
    public float speed = 4f;

    void Update()
    {
        // Arrows or WASD: move along x and z at speed, the same on diagonals.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics