Intrinsics1 min read

atan2

Computes the two-argument arc tangent.

Reading Time
1 min
Word Count
159
Sections
12
Try It Live

Test atan2 in a live shader

Open the playground, start from a visual preset, and wire atan2 into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The atan2 function returns the arc tangent of y/x, using the signs of both arguments to determine the correct quadrant. This gives a full 360° angle calculation.

Signature

bwsl
atan2 :: (T y, T x) -> T {...}

Where T can be float, float2, float3, or float4.

Parameters

ParameterTypeDescription
yTThe y-coordinate (numerator)
xTThe x-coordinate (denominator)

Return Value

Returns the arc tangent of y/x in radians, in the range [-π, π].

Example

bwsl
pipeline RadialGradient {
fragment {
// Convert UV to polar coordinates
float2 centered = input.uv - 0.5;
// Get angle using atan2 for full circle
float angle = atan2(centered.y, centered.x);
float radius = length(centered);
// Create color wheel
float hue = (angle / 6.28318) + 0.5; // Map [-π, π] to [0, 1]
float3 color = hsv2rgb(float3(hue, 1.0, 1.0 - radius * 2.0));
output.color = float4(color, 1.0);
}
}

Common Use Cases

Polar Coordinates

bwsl
// Convert Cartesian to polar
float angle = atan2(y, x);
float radius = length(float2(x, y));

Direction to Angle

bwsl
// Get rotation angle for sprite to face target
float2 toTarget = targetPos - currentPos;
float facingAngle = atan2(toTarget.y, toTarget.x);

Environment Mapping

bwsl
// Spherical environment map UV
float3 reflectDir = reflect(-viewDir, normal);
float u = atan2(reflectDir.z, reflectDir.x) / 6.28318 + 0.5;
float v = asin(reflectDir.y) / 3.14159 + 0.5;

Spiral Pattern

bwsl
// Create spiral effect
float2 centered = uv - 0.5;
float angle = atan2(centered.y, centered.x);
float radius = length(centered);
float spiral = sin(angle * arms + radius * twist + time);

Wind Direction

bwsl
// Calculate wind direction from vector
float windAngle = atan2(windDir.z, windDir.x);
float windSpeed = length(windDir.xz);

Parameter Order

Note the parameter order is atan2(y, x), not atan2(x, y). The Y component (vertical/sine) comes first.

Advantage Over atan

Unlike atan(y/x), atan2 handles all quadrants correctly and doesn't have division-by-zero issues when x = 0.

Compiled Output

When compiled to GLSL:

glsl
atan(y, x)

When compiled to HLSL:

hlsl
atan2(y, x)

When compiled to Metal:

metal
atan2(y, x)

See Also

  • atan - Single-argument arc tangent
  • sin - Sine
  • cos - Cosine