Mathf.Atan2

Switch to Manual

Declaration

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

Parameters

y Y-component of the input 2D vector.
x X-component of the input 2D vector.

Returns

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

Description

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

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: Tan, Atan.

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

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

Did you find this page useful? Please give it a rating: