Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


Atan2(float, float)

Returns the angle in radians whose Mathf.Tan is y/x.
Read time 1 minuteLast updated 4 days ago

Definition

  • Type: Method
  • Namespace: UnityEngine
  • Assembly: UnityEngine.CoreModule
public static float Atan2(float y, float x)

Parameters

Y-component of the input 2D vector.

X-component of the input 2D vector.

Returns

Type

Description

floatAngle in radians between the (
x
,
y
) vector and the (1,0) unit vector, in the range [-Pi, Pi].

Remarks

Return value is the angle between the x-axis unit vector (1, 0) and a 2D vector starting at zero and terminating at (x,y).
Note: This function takes account of the cases where x is zero and returns the correct angle rather than throwing a division by zero exception.
Additional Resources: Mathf.Tan, Mathf.Atan.

Examples

using UnityEngine;public class ExampleClass : MonoBehaviour{ public Transform target; public float turnSpeed = 2f; // higher = faster slerp void Update() { if (!target) return; // Compute desired yaw angle to target in local space Vector3 relative = transform.InverseTransformPoint(target.position); float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg; // Build target rotation around global up (yaw only) Quaternion targetRotation = Quaternion.Euler(0f, transform.eulerAngles.y + angle, 0f); // Smoothly rotate toward the target rotation transform.rotation = Quaternion.Slerp( transform.rotation, targetRotation, Time.deltaTime * turnSpeed ); }}