GLSL built-in function
cos()
Returns the cosine of an angle in radians: the same wave as sin, shifted a quarter turn ahead.
Syntax
float cos(float angle)
vec2 cos(vec2 angle)
vec3 cos(vec3 angle)
vec4 cos(vec4 angle)Parameters
- angle
- The angle in radians.
Return value
A value between -1.0 and 1.0.
Live example
Edit the code and the preview updates as you type.
How it works
cos has the same shape as sin but starts at the top: cos(0.0) is 1.0, while sin(0.0) is 0.0.
Used together they describe a circle. For any angle, the point vec2(cos(angle), sin(angle)) is exactly 1 unit away from the origin. As the angle grows, the point travels around the circle. The blue dot in the example does exactly that with u_time as the angle.
Giving x and y different speeds breaks the circle into a looping figure called a Lissajous curve, which is what the orange dot traces.
Typical uses
- Circular motion:
center + radius * vec2(cos(t), sin(t)). - Rotating coordinates: a 2D rotation matrix is
mat2(cos(a), -sin(a), sin(a), cos(a)). - Color palettes:
0.5 + 0.5 * cos(6.2831 * (t + vec3(0.0, 0.33, 0.67)))cycles smoothly through hues.
Common mistakes
- Swapping
cosandsinin circular motion. It still moves in a circle, but starts at a different point and can run in the opposite direction. - Mixing up the sign in a rotation matrix, which rotates the wrong way. Remember that GLSL matrices are filled column by column.
Related functions
sin()
Returns the sine of an angle in radians, a smooth wave that repeats every 2 * PI and stays between -1.0 and 1.0.
atan()
Returns the angle in radians whose tangent is y / x. The two-argument form atan(y, x) gives the full angle of a point around the origin, from -PI to PI.
length()
Returns the length of a vector, its distance from the origin. length(p) is the starting point for drawing circles.
Tutorials that use cos()
- Orbiting DotAnimate a small dot orbiting around the center.
- Rotating UVRotate UV around the center over time.
- Point Light FalloffAdd distance falloff to a point light so illumination changes naturally over space.
- Phong Lighting ModelImplement the basic Phong lighting model to simulate ambient, diffuse, and specular highlights on object surfaces.
- Toon ShadingImplement a non-photorealistic rendering technique that simulates the visual style of cartoons or comic books by quantizing light intensity into discrete color levels, often combined with edge detection.
- 2D Rotation MatrixRotate coordinates using a 2D rotation matrix.