Unity에서 벡터(Vector)의 크기를 계산할 때는 magnitude와 sqrMagnitude를 사용할 수 있다.
magnitude는 Vector의 크기를 반환한다. √(x*x+y*y+z*z)
sqrMagnitude는 Vector의 크기의 제곱을 반환한다. (x*x+y*y+z*z)
왜 sqrMagnitude가 빠른가?
제곱근 연산(sqrt)은 CPU에서 곱셈보다 연산비용이 더 크다.
따라서 단순히 두 벡터의 길이를 비교할 때는 sqrMagnitude를 사용하여 불필요한 제곱근 연산을 피하여 성능을 향상 시킬 수 있다.
Vector3 target;
float distance = 2;
if (target.magnitude > distance)
{
//생략
}
즉 위의 코드보다 아래와 같이 사용하는것이 더 빠르다.
Vector3 target;
float distance = 2;
if (target.sqrMagnitude > distance * distance)
{
//생략
}반응형