Legacy Documentation: Version 5.1
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

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

Sumbission failed

For some reason your suggested change could not be submitted. Please try again 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
public static function Atan2(y: float, x: float): float;
public static float Atan2(float y, float x);

Parameters

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 that this function takes account of the cases where x is zero and returns the correct angle rather than throwing a division by zero exception.

	// Usually you use transform.LookAt for this.
	// But this can give you more control over the angle

var target : Transform;

function Update () { var relative : Vector3 = transform.InverseTransformPoint(target.position); var angle : float = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg; transform.Rotate (0, angle, 0); }
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour { public Transform target; void Update() { Vector3 relative = transform.InverseTransformPoint(target.position); float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg; transform.Rotate(0, angle, 0); } }