Math module

unit_vector

procedure · 3 overloadsSource

v scaled to length 1, or v unchanged when it is zero (a zero vector has no direction, so it is returned as it is, signs of zero kept). Works at full precision for very small and very large components, which a plain divide by length would overflow or flush to zero. To also get the old length, or to supply a fallback, use normalize.

ExampleOpen in playground ↗
assert(unit_vector(xyz(0, 0, 5)) == xyz(0, 0, 1));
assert(unit_vector(xyz(0, 0, 0)) == xyz(0, 0, 0));
n := unit_vector(xy(3, 4));
assert(abs(n.x - 0.6) < 0.00001 && abs(n.y - 0.8) < 0.00001);
unit_vector :: (v: Vector2) -> Vector2

v scaled to length 1. A zero vector is returned unchanged.

Parameters

v: Vector2
the vector to scale.

Returns

unit_vector :: (v: Vector3) -> Vector3

v scaled to length 1. A zero vector is returned unchanged.

Parameters

v: Vector3
the vector to scale.

Returns

unit_vector :: (v: Vector4) -> Vector4

v scaled to length 1. A zero vector is returned unchanged.

Parameters

v: Vector4
the vector to scale.

Returns

See also