Version: Unity 6.0 (6000.0)
LanguageEnglish
  • C#

Mathf.Atan2

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

Switch to Manual

Declaration

public static float Atan2(float y, float x);

Description

Returns the angle in radians whose Tan is y/x.

Return value is the angle between the x-axis 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.

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 ); } }