GLSL Learning

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 cos and sin in 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

Tutorials that use cos()