GLSL Learning

GLSL built-in function

distance()

Returns the distance between two points, the same as length(p0 - p1).

Syntax

float distance(float p0, float p1)
float distance(vec2 p0, vec2 p1)
float distance(vec3 p0, vec3 p1)

Parameters

p0
The first point.
p1
The second point.

Return value

A single float greater than or equal to 0.

Live example

Edit the code and the preview updates as you type.

How it works

distance(a, b) tells you how far apart two points are. It is exactly length(a - b); use whichever reads better.

float d = distance(uv, vec2(0.5)); // distance from the canvas center

In the example, every pixel measures its distance to three moving points and keeps the smallest with min. Drawing contour lines on that value shows a set of circles that merge where the points meet, a simple form of a Voronoi distance field.

Typical uses

  • Circles around any point: step(distance(uv, center), radius).
  • Distance fields with several points: the nearest-point pattern in the example, the basis of cellular noise.
  • Mouse interaction: distance(uv, mouse) to highlight the area under the cursor.

Common mistakes

  • Mixing coordinate spaces. If uv is in 0..1 but the point is given in pixels, the distance is meaningless. Convert both to the same space first.
  • Forgetting the aspect ratio. On a wide canvas the same distance covers more pixels horizontally, so circles become ellipses.

Related functions

Tutorials that use distance()