본문 바로가기

유니티

[Unity] Atan() 함수와 Atan2() 함수의 차이점

우선, atan(아크탄젠트) 함수는 좌표평면에서 수평축으로부터 한 점까지의 각도를 구할 때 쓰인다.

Mathf.atan(y/x); 함수로 쉽고 간단하게 각도를 구할 수 있다.

 

비주얼 스튜디오 등의 IDE에서 프로그래밍하다 보면 Mathf.atan 와 Mathf.atan2 함수 두개가 있는걸 발견할 수 있는데, 그 두 함수의 차이점은 다음과 같다.

atan(y/x) 함수는 인자로 float 형식 변수 한개를 갖는다. 이 때 x좌표값이 0이라면 y/0이 되어 계산이 안되고 버그가 발생한다.

이런 이유로 atan2(y, x) 함수가 생기게 되었다.

atan2 함수는 인자를 y, x 두개를 받아 계산상에서 오류가 발생할 일이 없다.

 

예제 )

public class Example : MonoBehaviour{
	public GameObject target;
    void Update(){
        Vector2 distance = target.transform.position - transform.position;
        float z1 = Mathf.Atan(distance.y/distance.x) * Mathf.Rad2Deg;
        float z2 = Mathf.Atan2(distance.y, distance.x) * Mathf.Rad2Deg;
        Debug.Log(z1.ToString());
        Debug.Log(z2.ToString());
    }
}

다음 코드는 매 프레임마다 target 게임오브젝트 까지의 각도를 구해 출력한다.

z1과 z2의 출력은 같겠지만, atan 함수에서는 distance.x의 값이 0이라면 0으로 나눌 수 없어 버그가 발생하겠지만, y와 x 를 따로 입력받는 atan2 함수는 상관이 없다.