GLSL Shader Functions

Written by

in

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 x can be: A float, vec2, vec3, or vec4.
  • 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 a vec3, 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(), like float d = length(posB - posA); (same as calling distance(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…

Comments

One response to “GLSL Shader Functions”

  1. […] 3. Drawing Shapes Without Polygons: length(xy) […]

Leave a Reply

Your email address will not be published. Required fields are marked *