Core\Math::atan2
Returns the angle of a point, measured from the positive x-axis. You give it the point's two coordinates, $y first and then $x.
The angle is in radians, from -PI to PI. Points above the x-axis give a positive angle, and points below it give a negative angle. Core\Math::toDegrees converts the angle to degrees. The point (0, 0) gives 0.0.
Good to know: Core\Math::atan of $y / $x loses the signs of the two coordinates, so it cannot tell (1, 1) from (-1, -1). Core\Math::atan2 takes both coordinates, so it always gives the right direction. The order is easy to get wrong: $y comes first.
The examples below show the angles of four points, then points on the axes, then a compass direction from a map.
Parameters
$yfloatThe point's y coordinate.$xfloatThe point's x coordinate.
Return value
Returns float. An angle from -PI to PI, in radians. A point above the x-axis gives a positive angle, and a point below it gives a negative one. The point (0, 0) gives 0.0.
Examples
The angle of a point
<?nvs// Shows the angles `Core\Math::atan2` returns for one point on each side of the axes.
// The y coordinate comes first. This prints 45.echo Core\Math::toDegrees(Core\Math::atan2(1.0, 1.0)), "\n";
// You can name the arguments, so the order is clear. This prints 135.echo Core\Math::toDegrees(Core\Math::atan2(y: 1.0, x: -1.0)), "\n";
// A point below the x-axis gives a negative angle. This prints -135 and -45.echo Core\Math::toDegrees(Core\Math::atan2(-1.0, -1.0)), "\n";echo Core\Math::toDegrees(Core\Math::atan2(-1.0, 1.0)), "\n";45135-135-45Points on the axes
<?nvs// Shows the angles `Core\Math::atan2` returns for points that lie on an axis.
// A point straight up is at 90 degrees. This prints 90.echo Core\Math::toDegrees(Core\Math::atan2(1.0, 0.0)), "\n";
// A point to the left is at `PI` radians. This prints 3.1415926535898.echo Core\Math::atan2(0.0, -1.0), "\n";
// The point (0, 0) has no direction. The result is 0, and this prints 0.echo Core\Math::atan2(0.0, 0.0), "\n";903.14159265358980A compass direction
<?nvs// Shows how a delivery app finds the compass direction from the shop to a customer.// The map gives the distance east and the distance north, in metres.
class Compass{ // Returns the direction in degrees: 0 is north, 90 is east, 180 is south. public static function direction(float $east, float $north): float { // A compass starts at north, so the east distance is passed first. float $degrees = Core\Math::toDegrees(Core\Math::atan2($east, $north)); // `Core\Math::atan2` gives -90 for west. A compass uses 270. if ($degrees < 0.0) { $degrees = $degrees + 360.0; } return Core\Math::round($degrees); }}
// A customer 300 metres east and 300 metres north. This prints 45.echo Compass::direction(300.0, 300.0), "\n";
// A customer straight south. This prints 180.echo Compass::direction(0.0, -500.0), "\n";
// A customer to the west. This prints 270.echo Compass::direction(-200.0, 0.0), "\n";45180270