Skip to content

llAtan2

float llAtan2(float y, float x)

Returns the arc-tangent2 of y, x.

Parameters
y (float)
A floating-point value.
x (float)
A floating-point value.

Similar to arctangent(y/x) except it utilizes the signs of x and y to determine the quadrant and avoids division by zero.

Returns a value in the range [-PI, PI].

The function handles edge cases with zero values:

  • If x is positive zero:

    • If y is zero, zero is returned
    • If y is positive, PI/2 is returned
    • If y is negative, -PI/2 is returned
  • If x is negative zero:

    • If y is positive zero, PI is returned
    • If y is negative zero, -PI is returned
    • If y is positive, PI/2 is returned
    • If y is negative, -PI/2 is returned

Alternatively, this can be expressed as:

if((string)x != (string)0.0 && y == 0.0) // negative zero
return PI * ~-2*((string)y != (string)0.0));
return ((y > 0) - (y < 0)) * PI_BY_TWO;

Basic usage with random values:

default
{
state_entry()
{
float num1 = llFrand(100.0);
float num2 = llFrand(100.0);
llOwnerSay("y = " + (string)num1);
llOwnerSay("x = " + (string)num2);
llOwnerSay("The arctangent of y divided by x is " + (string)llAtan2(num1, num2));
}
}

Compass direction calculator (returns compass bearing based on target position):

// Function with input of a vector determining the position of a target and returning
// a string with the literal compass-direction of that target towards your position
// by Ramana Sweetwater 2009/01, any use allowed license :-)
// corrected by Patrick Muggins
string compass(vector target)
{
vector source = llGetPos();
list DIRS = ["W", "NW", "N", "NE", "E", "SE", "S", "SW", "W"];
integer index = llCeil(3.5 - (4 * llAtan2(target.y - source.y, target.x - source.x) / PI));
return llList2String(DIRS, index);
}