'2019/05'에 해당되는 글 1건

  1. 2019/05/02 글뻥 How to get a angle from 2 gameobject positions on Unity3D

Many article says how to get a angle by Atan2.
that was to explain how to get a angle on Vector2. and not consider Transform forward.


Solution 1. Using Atan2 correctly

Vector3 delta = t.position - transform.position;

float angle = (Mathf.Atan2(transform.forward.x, transform.forward.z) - Mathf.Atan2(delta.x, delta.z)) * Mathf.Rad2Deg;
if (angle >= 360f)
{
    Debug.Log(angle - 360f);
} else if (angle <= 0f )
{
    Debug.Log(360f + angle);
} else 
{
    Debug.Log(angle);
}


Solution 2. Using Quaternion
Debug.Log(Quaternion.FromToRotation(transform.forward, t.position - transform.position).eulerAngles.y);


Solution 3. Using SignedAngle
Debug.Log(Vector3.SignedAngle(transform.forward, delta, Vector3.up));

2019/05/02 17:05 2019/05/02 17:05