GLSL built-in function
cross()
Returns the cross product of two 3D vectors: a new vector perpendicular to both. Used to build normals and coordinate frames.
Syntax
vec3 cross(vec3 x, vec3 y)Parameters
- x
- The first 3D vector.
- y
- The second 3D vector.
Return value
A vec3 perpendicular to both x and y. Its length is length(x) * length(y) * sin(angle between them).
Live example
Edit the code and the preview updates as you type.
How it works
cross(a, b) builds a third vector that sticks straight out of the plane formed by a and b:
cross(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)) // vec3(0.0, 0.0, 1.0)
The order matters. cross(b, a) points the opposite way. With a right-handed system, curl the fingers of your right hand from a to b and your thumb points along the result.
The example lights a wavy surface without any mesh. At every pixel it builds two vectors that run along the surface (one in x, one in y, tilted by the slope), and cross gives the vector perpendicular to both: the surface normal. Lighting that normal with dot reveals the bumps.
Typical uses
- Normals of surfaces and triangles:
normalize(cross(edge1, edge2)). - Camera frames: from a forward direction and an up vector,
right = normalize(cross(forward, up))andup = cross(right, forward). - Checking which side: the sign of
cross(a, b).ztells whether b is to the left or right of a in 2D.
Common mistakes
- Using it on vec2 or vec4.
crossonly exists for vec3. - Getting the order backwards, which flips the normal so the surface looks lit from behind.
- Crossing two parallel vectors. The result is a zero vector, and normalizing it produces NaN.