length
Computes the magnitude of a vector.
Test length in a live shader
Open the playground, start from a visual preset, and wire length into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The length function returns the magnitude (Euclidean length) of a vector, computed as the square root of the sum of squared components.
Signature
length :: (vecN v) -> float {...}
Where vecN can be float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
v | vecN | The vector to measure |
Return Value
Returns sqrt(v.x*v.x + v.y*v.y + ...) for all components.
Example
pipeline PointLight {
fragment {
// Calculate distance to light
float3 toLight = lightPos - input.worldPos;
float dist = length(toLight);
// Attenuation based on distance
float attenuation = 1.0 / (1.0 + 0.1 * dist + 0.01 * dist * dist);
// Direction to light (normalized)
float3 lightDir = toLight / dist; // Same as normalize(toLight)
float diffuse = max(dot(input.normal, lightDir), 0.0);
output.color = float4(lightColor * diffuse * attenuation, 1.0);
}
}Common Use Cases
Distance to Point
// Calculate distance (use distance() for cleaner code)
float dist = length(pointB - pointA);Light Attenuation
// Distance-based light falloff
float dist = length(lightPos - fragPos);
float attenuation = 1.0 / (dist * dist);Radial Effects
// Distance from center for radial effects
float radius = length(input.uv - 0.5);
float vignette = 1.0 - smoothstep(0.3, 0.7, radius);Velocity Magnitude
// Get speed from velocity vector
float speed = length(velocity);SDF Operations
// Sphere distance field
float sphereDist = length(position - sphereCenter) - sphereRadius;Performance
If you only need to compare lengths (not the actual value), compare squared lengths instead: dot(v, v) < threshold * threshold. This avoids the expensive sqrt operation.
Manual Calculation
length(v) is equivalent to sqrt(dot(v, v)). When you already have the dot product, you can compute length directly.
Compiled Output
When compiled to GLSL:
length(v)
When compiled to HLSL:
length(v)