length()
In GLSL (the shader language used in OpenGL and WebGL), length(x) calculates the magnitude (or Euclidean length) of a vector x essentially how “long” the arrow is from the origin (0, 0, ...) to that point.
- What
xcan be: Afloat,vec2,vec3, orvec4. - What it returns: A single
float(always zero or positive). - How it works: For a 2D vector
(x, y), it computes sqrt(x^2 + y^2) (the Pythagorean theorem). For avec3, it extends that to sqrt(x^2 + y^2 + z^2).
Why beginners use it often
- Distance between two points: Subtract two positions and pass the difference into
length(), likefloat d = length(posB - posA);(same as callingdistance(posA, posB)). - Circular or spherical shapes: In a fragment shader, checking
length(uv)tells you how far a pixel is from the center, great for drawing circles, glow falloffs, or radial gradients. - Checking vector size: Quickly test if a velocity, offset, or direction vector has grown past a certain limit (
if (length(vel) > 1.0)).
(Tip: When you only care about comparing lengths – like checking if length(v) < radius—comparing dot(v, v) < radius * radius skips the square root and can be slightly faster in tight loops.)
Example here…
Leave a Reply