Intrinsics1 min read

distance

Computes the distance between two points.

Reading Time
1 min
Word Count
116
Sections
12
Try It Live

Test distance in a live shader

Open the playground, start from a visual preset, and wire distance into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The distance function returns the Euclidean distance between two points, equivalent to length(b - a).

Signature

bwsl
distance :: (vecN a, vecN b) -> float {...}

Where vecN can be float2, float3, or float4.

Parameters

ParameterTypeDescription
avecNFirst point
bvecNSecond point

Return Value

Returns the Euclidean distance between a and b.

Example

bwsl
pipeline ProximityGlow {
fragment {
// Calculate distance to interaction point
float3 worldPos = input.worldPos;
float dist = distance(worldPos, cursorWorldPos);
// Create glow effect based on proximity
float glow = 1.0 - smoothstep(0.0, glowRadius, dist);
float3 baseColor = sample(albedoTex, input.uv).rgb;
float3 finalColor = baseColor + glowColor * glow;
output.color = float4(finalColor, 1.0);
}
}

Common Use Cases

Point Light Radius

bwsl
// Check if point is within light radius
float dist = distance(fragPos, lightPos);
if (dist < lightRadius) {
// Apply lighting
}

Fog Effect

bwsl
// Distance-based fog
float viewDist = distance(input.worldPos, cameraPos);
float fogFactor = saturate((viewDist - fogStart) / (fogEnd - fogStart));
float3 color = lerp(objectColor, fogColor, fogFactor);

Circle/Sphere Masking

bwsl
// Circular mask
float dist = distance(input.uv, float2(0.5, 0.5));
float circle = 1.0 - smoothstep(0.4, 0.5, dist);

LOD Selection

bwsl
// Select LOD based on camera distance
float dist = distance(objectCenter, cameraPos);
int lod = int(clamp(dist / lodDistance, 0.0, float(maxLOD)));

Particle Effects

bwsl
// Fade particles near geometry
float distToSurface = distance(particlePos, nearestSurfacePoint);
float fade = smoothstep(0.0, fadeDistance, distToSurface);

Squared Distance

For distance comparisons, use squared distance to avoid the sqrt: dot(b-a, b-a) < threshold * threshold instead of distance(a, b) < threshold.

Equivalent Forms

distance(a, b) is equivalent to length(b - a) and length(a - b).

Compiled Output

When compiled to GLSL:

glsl
distance(a, b)

When compiled to HLSL:

hlsl
distance(a, b)

See Also