In the previous lesson we measured distances by subtracting coordinates and applying Pythagoras. Those "differences of coordinates" were vectors, and it is time to treat them as such. In "Vectors and Vector Spaces" we learned to add them, scale them and combine them; what we left pending was measuring them. This lesson introduces the norm—the length of a vector—normalization—keeping only the direction—and the idea that ties them together: every vector breaks down into how much and which way. With that we will finally be able to do something every game needs on every frame: move the ship toward a target at a given speed.

The code assumes that the function displacement(origin, destination) from Module 1, which returns destination - origin, is already defined.

Three roles for three numbers: position, displacement and direction

A triple \((x, y, z)\) can mean three different things, and a good share of the bugs in a 3D engine come from mixing them up.

Role What it represents Example in the scene Is it affected by a translation?
Position vector A point, described by the arrow that goes from the origin to it Ship: \((8, 3, 6)\) Yes
Displacement vector The change needed to go from one point to another; it has length and direction, but no fixed place From the ship to the lighthouse: \((-8, -3, -6)\) No
Direction Only "which way"; the length does not matter and is fixed at 1 The ship's longitudinal axis: \((0.8, 0, 0.6)\) No

We already know the ground rules from Module 1: point − point = displacement and point + displacement = point. And from Module 2 we know how the engine tells the cases apart when transforming: points carry \(w = 1\) in homogeneous coordinates, and displacements and directions carry \(w = 0\).

What is new in this lesson is the relationship between the last two roles: a direction is a displacement with its length removed. To remove it, we first need to know how to measure it.

Notations: components and the vectors (\mathbf{i}), (\mathbf{j}), (\mathbf{k})

You will find 3D vectors written in several equivalent ways:

  • By components, as a row or as a column: \(\mathbf{v} = (v_x, v_y, v_z)\). This is the one we use in the course (as a column when matrices are involved).
  • With the vectors of the standard basis, which in physics and engineering are called \(\mathbf{i} = (1, 0, 0)\), \(\mathbf{j} = (0, 1, 0)\) and \(\mathbf{k} = (0, 0, 1)\):

\[ \mathbf{v} = v_x,\mathbf{i} + v_y,\mathbf{j} + v_z,\mathbf{k} \]

The second form is simply the vector written as a linear combination of the basis. The ship's example velocity, \((2, 0, -1)\), is \(2\mathbf{i} - \mathbf{k}\): every second it advances 2 m along X and goes back 1 m along Z.

There are also two notations for the length: \(\lVert \mathbf{v} \rVert\) (double bars, "norm") and \(\lvert \mathbf{v} \rvert\) (single bars, "magnitude"). They mean the same thing; we will use the first so as not to confuse it with the absolute value of a number.

The norm of a vector

The norm (or magnitude, or length) of a vector is the distance between its tail and its tip. The calculation is the double Pythagoras from the previous lesson, applied to the components:

\[ \lVert \mathbf{v} \rVert = \sqrt{v_x^2 + v_y^2 + v_z^2} \]

Examples.

  • Displacement from the ship to the lighthouse, \((-8, -3, -6)\): \(\sqrt{64 + 9 + 36} = \sqrt{109} \approx 10.44\).
  • The ship's velocity, \((2, 0, -1)\): \(\sqrt{4 + 0 + 1} = \sqrt{5} \approx 2.24\).
  • Column \(n_1 = (0.6, 0, -0.8)\) of the ship's orientation: \(\sqrt{0.36 + 0.64} = 1\).

The signs of the components have no effect, because they are squared.

Properties

Property Statement What it means
Non-negativity \(\lVert \mathbf{v} \rVert \ge 0\) A length is never negative
Only the zero vector has length zero \(\lVert \mathbf{v} \rVert = 0\) only if \(\mathbf{v} = \mathbf{0}\) If there is no length, there is no displacement
Homogeneity \(\lVert k,\mathbf{v} \rVert = \lvert k \rvert,\lVert \mathbf{v} \rVert\) Scaling by \(k\) multiplies the length by \(\lvert k \rvert\)
Triangle inequality \(\lVert \mathbf{a} + \mathbf{b} \rVert \le \lVert \mathbf{a} \rVert + \lVert \mathbf{b} \rVert\) Going straight there is never longer than taking a detour

Two comments:

  • Homogeneity involves the absolute value: \(-2\mathbf{v}\) is twice as long as \(\mathbf{v}\), not "minus twice as long". The sign of \(k\) reverses the direction, but it does not make the length negative.
  • The triangle inequality says that the norm of a sum is not the sum of the norms (unless the two vectors point the same way). Suppose the ship goes to beacon Alpha, located at \((12, 7, 4)\), passing first by the escort drone, at \((10, 3, 6)\). The legs are \(\mathbf{a} = (2, 0, 0)\), of norm 2, and \(\mathbf{b} = (2, 4, -2)\), of norm \(\sqrt{24} \approx 4.90\). The direct trip is \(\mathbf{a} + \mathbf{b} = (4, 4, -2)\), of norm \(\sqrt{36} = 6\), less than \(2 + 4.90 = 6.90\).
import numpy as np

def norm(v):
    """Length of a vector."""
    v = np.asarray(v, dtype=float)
    return float(np.sqrt(np.sum(v * v)))

ship = np.array([8.0, 3.0, 6.0])
lighthouse = np.array([0.0, 0.0, 0.0])
drone = np.array([10.0, 3.0, 6.0])
beacon_alpha = np.array([12.0, 7.0, 4.0])
velocity = np.array([2.0, 0.0, -1.0])

print(round(norm(displacement(ship, lighthouse)), 4))
print(round(norm(velocity), 4), round(norm(-3.0 * velocity), 4))

a = displacement(ship, drone)
b = displacement(drone, beacon_alpha)
print(norm(a + b), round(norm(a) + norm(b), 4))
10.4403
2.2361 6.7082
6.0 6.899

The second line illustrates homogeneity: \(\lVert -3\mathbf{v} \rVert = 3 \cdot 2.2361 = 6.7082\).

NumPy offers np.linalg.norm(v), which does exactly the same thing. We write our own so that there is no black box; in the next lesson we will see that this sum of squares is a special case of the dot product.

Distance: the norm of a difference

With the norm, the distance formula from the previous lesson fits on one line: the distance between two points is the length of the displacement that joins them.

\[ d(A, B) = \lVert B - A \rVert \]

The properties of distance follow from those of the norm: it is never negative, it is 0 only if the points coincide, it is symmetric (\(\lVert B - A \rVert = \lVert A - B \rVert\), by homogeneity with \(k = -1\)) and it satisfies the triangle inequality: \(d(A, C) \le d(A, B) + d(B, C)\).

def distance(a, b):
    """Distance between two points."""
    return norm(np.asarray(b, dtype=float) - np.asarray(a, dtype=float))

camera = np.array([0.0, 5.0, 20.0])
print(distance(ship, beacon_alpha), round(distance(ship, camera), 4))
6.0 16.2481

Unit vectors and normalization

A unit vector is one whose norm is 1. It is usually marked with a hat: \(\hat{\mathbf{u}}\). Unit vectors are the standard way of representing a pure direction: the axes \(\mathbf{i}\), \(\mathbf{j}\), \(\mathbf{k}\), the columns \(n_1\), \(n_2\), \(n_3\) of the ship's orientation, the direction in which the camera looks or, later on, the normal of a surface.

Normalizing a vector means obtaining the unit vector that points the same way. All it takes is dividing it by its norm:

\[ \hat{\mathbf{v}} = \frac{\mathbf{v}}{\lVert \mathbf{v} \rVert} \]

That the result has length 1 follows from homogeneity: \(\left\lVert \frac{1}{\lVert \mathbf{v} \rVert}\mathbf{v} \right\rVert = \frac{1}{\lVert \mathbf{v} \rVert}\lVert \mathbf{v} \rVert = 1\).

Example. The displacement from the ship to beacon Alpha is \((4, 4, -2)\), of norm 6. Normalized:

\[ \hat{\mathbf{u}} = \frac{(4, 4, -2)}{6} = \left(\tfrac{2}{3},\ \tfrac{2}{3},\ -\tfrac{1}{3}\right) \approx (0.667,\ 0.667,\ -0.333) \]

Check: \(\frac{4}{9} + \frac{4}{9} + \frac{1}{9} = 1\).

The zero vector has no direction

For the vector \(\mathbf{0}\) the formula asks us to divide by 0. This is not a technicality: the zero vector does not point anywhere, so there is no direction to return. In practice, this case comes up constantly (the ship is already on the target, the velocity is zero, two points coincide) and, if it is not handled, it fills the scene with nan values that spread through every later calculation.

What is more, because of rounding errors it is not enough to compare with an exact 0: we compare with a small tolerance.

def normalize(v, tolerance=1e-12):
    """Unit vector pointing the same way as v."""
    v = np.asarray(v, dtype=float)
    length = norm(v)
    if length < tolerance:
        raise ValueError("cannot normalize the zero vector")
    return v / length

def direction_to(origin, destination):
    """Unit direction pointing from origin toward destination."""
    return normalize(displacement(origin, destination))

u = direction_to(ship, beacon_alpha)
print(np.round(u, 4), round(norm(u), 6))
[ 0.6667  0.6667 -0.3333] 1.0

Our normalize raises an error so that the problem does not go unnoticed. Another common policy is to return a default vector; what matters is to decide it consciously and not let a division by zero decide for us.

Magnitude and direction: velocity

Normalizing splits a vector into its two ingredients, and multiplying puts them back together:

\[ \mathbf{v} = \underbrace{\lVert \mathbf{v} \rVert}{\text{magnitude}}\ \underbrace{\hat{\mathbf{v}}}{\text{direction}} \]

The example par excellence is velocity. In everyday language "velocity" and "speed" get mixed up; in an engine it pays to tell them apart:

  • Velocity: a vector. It says how far the object moves per second along each axis.
  • Speed: a number, the norm of the velocity. It is what the speedometer would show.
  • Direction of motion: a unit vector, the normalized velocity.

\[ \text{velocity} = \text{speed} \times \text{direction} \]

For the ship, with velocity \((2, 0, -1)\): the speed is \(\sqrt{5} \approx 2.24\) m/s and the direction is \((2, 0, -1)/\sqrt{5} \approx (0.894, 0, -0.447)\).

The decomposition is useful above all the other way round, for building velocities. A designer does not think "I want the velocity \((3.33, 3.33, -1.67)\)", but "I want the ship to head for beacon Alpha at 5 m/s": a direction and a speed, which are controlled separately.

\[ \mathbf{v} = 5 \cdot \left(\tfrac{2}{3},\ \tfrac{2}{3},\ -\tfrac{1}{3}\right) \approx (3.33,\ 3.33,\ -1.67) \]

In the same way we cap a maximum speed (if the norm exceeds the limit, we normalize and multiply by the limit) or change course without altering the speed (the norm is kept and the direction is replaced).

Direction cosines

What do the components of a unit vector mean? Each one is the cosine of the angle the vector makes with the corresponding axis. That is why they are called direction cosines:

\[ \cos\alpha = \frac{v_x}{\lVert \mathbf{v} \rVert} \qquad \cos\beta = \frac{v_y}{\lVert \mathbf{v} \rVert} \qquad \cos\gamma = \frac{v_z}{\lVert \mathbf{v} \rVert} \]

where \(\alpha\), \(\beta\) and \(\gamma\) are the angles with the positive X, Y and Z half-axes. The reason is basic trigonometry: the component \(v_x\) is the leg adjacent to the angle \(\alpha\) in a right triangle whose hypotenuse is the vector itself.

Since they are the components of a vector of norm 1, the three cosines are linked:

\[ \cos^2\alpha + \cos^2\beta + \cos^2\gamma = 1 \]

In other words, only two of the three angles are independent: a direction in space has two degrees of freedom, the same as the azimuth and the elevation of spherical coordinates.

Example. For the direction from the ship to beacon Alpha, \(\left(\tfrac{2}{3}, \tfrac{2}{3}, -\tfrac{1}{3}\right)\):

Axis Direction cosine Angle Reading
X \(2/3 \approx 0.667\) \(48.19°\) It advances along +X
Y \(2/3 \approx 0.667\) \(48.19°\) It climbs: the beacon is higher up
Z \(-1/3 \approx -0.333\) \(109.47°\) More than 90°: it goes against +Z

A positive cosine indicates that the vector advances along the axis; a negative one, against it; and zero, that it is perpendicular to it. The ship's velocity, with direction cosine 0 in Y, is horizontal.

print(np.round(np.degrees(np.arccos(u)), 2), round(float(np.sum(u * u)), 6))
[ 48.19  48.19 109.47] 1.0

Moving along a direction

The line of motion

If an object starts from the point \(\mathbf{p}_0\) and moves with constant velocity \(\mathbf{v}\), after a time \(t\) it is at:

\[ \mathbf{p}(t) = \mathbf{p}_0 + t,\mathbf{v} \]

It is the rule "point + displacement = point", with a displacement that grows in proportion to time. With the ship at \((8, 3, 6)\) and velocity \((2, 0, -1)\): after 2 s it is at \((8, 3, 6) + 2,(2, 0, -1) = (12, 3, 4)\), and after 4 s, at \((16, 3, 2)\). The distance covered in a time \(t\) is \(\lVert t,\mathbf{v} \rVert = t \cdot \text{speed}\).

If a unit direction \(\hat{\mathbf{u}}\) is used instead of the velocity, the parameter measures distance directly: \(\mathbf{p}_0 + s,\hat{\mathbf{u}}\) is the point located \(s\) meters from the start. This expression will return in "Equations of Planes and Lines" as the equation of a line.

Step by step: move_toward

A game does not compute the trajectory all at once, but frame by frame. In each one a small time dt elapses and the object advances one step of length speed * dt in the direction of the target:

  1. Compute the distance to the target.
  2. If the step is greater than or equal to that distance, place the object exactly on the target.
  3. Otherwise, advance: position + step * direction.

The second point avoids two problems at once: overshooting (and oscillating around the target forever) and normalizing the zero vector once we have arrived.

def move_toward(position, target, speed, dt):
    """Advances toward the target at constant speed, without overshooting it."""
    position = np.asarray(position, dtype=float)
    target = np.asarray(target, dtype=float)
    step = speed * dt
    if distance(position, target) <= step:
        return target.copy()
    return position + step * direction_to(position, target)

# The ship heads for beacon Alpha at 3 m/s, with half-second frames
position = ship.copy()
for frame in range(1, 6):
    position = move_toward(position, beacon_alpha, 3.0, 0.5)
    print(frame, position, round(distance(position, beacon_alpha), 4))
1 [9.  4.  5.5] 4.5
2 [10.  5.  5.] 3.0
3 [11.   6.   4.5] 1.5
4 [12.  7.  4.] 0.0
5 [12.  7.  4.] 0.0

Each frame covers \(3 \cdot 0.5 = 1.5\) m: the step is \(1.5 \cdot \left(\tfrac{2}{3}, \tfrac{2}{3}, -\tfrac{1}{3}\right) = (1, 1, -0.5)\). The distance drops from 6 to 0 in four frames and on the fifth the ship stays at the beacon, with no errors and no jitter. Notice that the speed is the same in every direction: if we had added "1.5 on each axis", the ship would travel faster diagonally than in a straight line, a classic bug in badly programmed games.

Squared length: comparing without roots

The square root is, by far, the most expensive operation in the norm. Often it is not needed: if all we want is to compare lengths, we can compare their squares, because for non-negative numbers

\[ \lVert \mathbf{a} \rVert < \lVert \mathbf{b} \rVert \iff \lVert \mathbf{a} \rVert^2 < \lVert \mathbf{b} \rVert^2 \]

and the squared norm is nothing but sums and products: \(\lVert \mathbf{v} \rVert^2 = v_x^2 + v_y^2 + v_z^2\).

Typical uses: deciding which object is closest, or whether something is within a radius (we compare with the squared radius). For example, which objects does a ship radar with a 7 m range detect? We compare with \(7^2 = 49\):

Object Displacement from the ship Squared distance Less than 49?
Escort drone \((2, 0, 0)\) 4 Yes
Beacon Alpha \((4, 4, -2)\) 36 Yes
Base of the lighthouse \((-8, -3, -6)\) 109 No
Lighthouse lamp \((-8, 9, -6)\) 181 No
Camera \((-8, 2, 14)\) 264 No
def squared_norm(v):
    """Square of the length: useful for comparing without computing roots."""
    v = np.asarray(v, dtype=float)
    return float(np.sum(v * v))

objects = {"drone": drone, "beacon_alpha": beacon_alpha, "lighthouse": lighthouse, "camera": camera}
radar_range = 7.0
print([name for name, p in objects.items()
       if squared_norm(p - ship) <= radar_range * radar_range])
print(min(objects, key=lambda name: squared_norm(objects[name] - ship)))
['drone', 'beacon_alpha']
drone

Two precautions: squares are fine for comparing, but they cannot be added as if they were distances (\(4 + 36\) is not the square of anything useful); and when the actual distance is needed—to normalize, to show it on screen, to compute an arrival time—the root is unavoidable.

Common Mistakes and Tips

  • Adding two positions. "Ship + lighthouse" means nothing. Displacements are added to points, and points are subtracted to obtain displacements.
  • Normalizing without checking for the zero vector. It is the most common source of nan in an engine. Check the norm before dividing.
  • Assuming that a vector is a unit vector. Many formulas in the coming lessons are only valid with normalized vectors. After several operations, rounding pushes the norm away from 1: renormalize when the vector is going to be used as a direction.
  • Believing that \(\lVert \mathbf{a} + \mathbf{b} \rVert = \lVert \mathbf{a} \rVert + \lVert \mathbf{b} \rVert\). It only happens if they point the same way.
  • Normalizing positions. Normalizing \((8, 3, 6)\) gives the direction from the origin toward the ship, not "the ship". It is displacements that get normalized.
  • Moving by adding a fixed amount to each component. The speed would depend on the direction. Always: unit direction times speed times dt.
  • Forgetting the dt. If the step is not multiplied by the frame time, the object will go faster on faster computers.
  • Tip. Use names that give away the role of each vector (position_, direction_, velocity_) and, by convention, treat everything called direction as normalized.

Exercises

Exercise 1. The camera is at \((0, 5, 20)\) and the stray asteroid, at \((-6, 2, 10)\). a) Compute the displacement from the camera to the asteroid, its norm and the unit direction. b) What angle does that direction make with the Y axis? Is the asteroid above or below the camera?

Exercise 2. The ship \((8, 3, 6)\) must head for the lighthouse lamp \((0, 12, 0)\) at a speed of 4.5 m/s. a) Compute its velocity vector. b) Where will it be after 1 s? c) How long will it take to arrive?

Exercise 3. The camera chases the ship (which we assume to be stationary) with move_toward, at 4 m/s and with dt = 1. a) Compute by hand the camera's position after the first frame. b) How many frames does it need to reach it, and what happens on the last one? c) Without computing any roots, decide which of these objects are less than 13 m from the ship: base of the lighthouse, lamp and camera.

Solutions

Solution 1.

a) Displacement: \((-6 - 0,\ 2 - 5,\ 10 - 20) = (-6, -3, -10)\). Norm: \(\sqrt{36 + 9 + 100} = \sqrt{145} \approx 12.04\). Direction: \((-6, -3, -10)/12.04 \approx (-0.498, -0.249, -0.830)\).

b) The direction cosine with respect to Y is \(-0.249\), so \(\beta = \arccos(-0.249) \approx 104.4°\). It is greater than 90°: the direction points slightly downward, and the asteroid is below the camera (indeed, it is at height 2 versus 5).

Solution 2.

a) Displacement: \((-8, 9, -6)\), of norm \(\sqrt{181} \approx 13.454\). Direction: \((-0.5946, 0.6690, -0.4460)\). Velocity: \(4.5\) times the direction, \(\approx (-2.676, 3.010, -2.007)\).

b) \(\mathbf{p}(1) = (8, 3, 6) + (-2.676, 3.010, -2.007) = (5.324, 6.010, 3.993)\).

c) \(t = \text{distance} / \text{speed} = 13.454 / 4.5 \approx 2.99\) s. Typical mistake: dividing the distance by one of the components of the velocity instead of by the speed.

lamp = np.array([0.0, 12.0, 0.0])
velocity_to_lamp = 4.5 * direction_to(ship, lamp)
print(np.round(velocity_to_lamp, 3), np.round(ship + velocity_to_lamp, 3))
print(round(distance(ship, lamp) / 4.5, 2))
[-2.676  3.01  -2.007] [5.324 6.01  3.993]
2.99

Solution 3.

a) Displacement from the camera to the ship: \((8, -2, -14)\), of norm \(\sqrt{264} \approx 16.248\). Direction: \((0.4924, -0.1231, -0.8616)\). The step measures \(4 \cdot 1 = 4\) m, less than the distance, so the camera advances: \((0, 5, 20) + 4,(0.4924, -0.1231, -0.8616) = (1.969, 4.508, 16.553)\).

b) The distance is 16.248 m and each step covers 4 m: after four frames \(16.248 - 16 = 0.248\) m remain. On the fifth, the step (4 m) exceeds the remaining distance, and move_toward places the camera exactly on the ship instead of overshooting it. That makes 5 frames.

c) We compare with \(13^2 = 169\). Base of the lighthouse: 109, inside. Lamp: 181, outside. Camera: 264, outside.

print(np.round(move_toward(camera, ship, 4.0, 1.0), 3))
[ 1.969  4.508 16.553]

Conclusion

A triple of numbers can be a position, a displacement or a direction, and telling those roles apart avoids most mistakes. The norm measures the length of a vector and turns the distance between two points into the norm of their difference; normalizing splits a vector into magnitude and direction, and that split is what lets us think in terms of "go that way at such-and-such a speed", which is how designers reason and how move_toward works. Direction cosines give meaning to the components of a unit vector, and the squared norm lets us compare distances without paying the price of a root. One question remains that the norm alone cannot answer: direction cosines measure the angle between a vector and the axes, but what about the angle between any two vectors? Is the lighthouse in front of the ship or behind it? Which direction is perpendicular to two given ones? That is the job of the two operations in the next lesson, "Dot Product and Cross Product".

© Copyright 2026. All rights reserved