GLSL Learning

GLSL built-in function

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.

Syntax

float atan(float y, float x)
float atan(float y_over_x)
vec2 atan(vec2 y, vec2 x)

Parameters

y
The vertical component. Note that it comes first.
x
The horizontal component.

Return value

An angle in radians. atan(y, x) returns -PI to PI; atan(y_over_x) returns -PI/2 to PI/2.

Live example

Edit the code and the preview updates as you type.

How it works

Where length(p) answers "how far is this pixel from the center", atan(p.y, p.x) answers "in which direction". Together they are polar coordinates.

The result is an angle in radians:

directionatan(y, x)
right0.0
up1.5708 (PI / 2)
left3.1416 or -3.1416 (PI)
down-1.5708

a / 6.2831 + 0.5 turns that into a 0..1 value: the percentage of a full turn. The example uses it to pick a hue, which gives a color wheel, and repeats it 12 times with fract to draw rotating rays.

Typical uses

  • Radial patterns: rays, pie slices, flower petals with sin(a * petals).
  • Polar coordinates: vec2(length(p), atan(p.y, p.x)) turns spirals and rings into simple straight-line problems.
  • Pointing toward something: the angle between a pixel and a target point.

Common mistakes

  • Swapping the arguments. It is atan(y, x) with y first, the same order as atan2 in C or JavaScript's Math.atan2.
  • Using the one-argument form for full angles. atan(p.y / p.x) cannot tell left from right and divides by zero on the vertical axis.
  • Calling atan(0.0, 0.0). The result is undefined, so the exact center pixel may flicker.
  • Expecting a seamless value. The angle jumps from PI to -PI on the left side, so patterns based on it need a whole number of repeats to avoid a visible seam.

Related functions

Tutorials that use atan()