Menu
CoddyTech

Diagonal Speed

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 27 of 85.

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

Make the walker move at the same speed on diagonals.

  1. In Update(), build Vector3 direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));.
  2. Add direction.normalized * speed * Time.deltaTime to transform.position.

Press Play and hold two arrows: the walker goes diagonally no faster than straight. Then 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.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground