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
uvis 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
length()
Returns the length of a vector, its distance from the origin. length(p) is the starting point for drawing circles.
min()
Returns the smaller of x and y. With vectors, each component is compared separately.
smoothstep()
Returns 0.0 below edge0, 1.0 above edge1, and a smooth S-shaped curve in between.
Tutorials that use distance()
- Mouse InteractionLearn to create interactive effects using mouse coordinates and understand the passing and usage of uniform variables.
- Orbiting DotAnimate a small dot orbiting around the center.
- Centered Circle MaskCreate a mask area centered on the canvas using distance().
- Smoothstep Edge FadeUse smoothstep() to achieve a fade transition at the edges of a shape, contrasting with step().
- Radial Gradient CenterCreate an outward-spreading radial gradient starting from the canvas center using distance().
- Gradient EffectsLearn to create various gradient effects, including linear gradients, radial gradients, angular gradients, and dynamic blending