Distance / Length - Built-in functions - Shader Learning

Built-in functions

Distance / Length

Task

Try to fill pixels in red that are within 0.25 of the texture center in normalized coordinates.

Theory

The length Function


The length function in GLSL calculates the Euclidean length (magnitude) of a vector.

Function Signature

float length(vec v)

It takes a single argument, which is the vector for which you want to calculate the length.

Example

vec3 vec = vec3(2.0, 4.0, 4.0);
float vecLength = length(vec); // will be 6.0

The distance Function


The distance function in GLSL calculates the Euclidean distance between two points or vectors.

Function Signature

float distance(vec p0, vec p1)

It takes two arguments, which are the two points or vectors between which you want to calculate the distance.

Example

vec3 p0 = vec3(1.0, 2.0, 2.0);
vec3 p1 = vec3(4.0, 2.0, 6.0);
float dist = distance(p0, p1); // will be 5.0

Interchangeability


The length and distance functions are interchangeable:

length(p1 - p0) = distance(p0, p1)