float SightAngle = 70f; //시야각 범위
Transform AttackTargetPlayer;
bool IsTargetInSight()
{
//타겟의 방향
Vector3 targetDir = (AttackTargetPlayer.position - Tr.position).normalized;
float dot = Vector3.Dot(Tr.forward, targetDir);
//내적을 이용한 각 계산하기
// thetha = cos^-1( a dot b / |a||b|)
float theta = Mathf.Acos(dot) * Mathf.Rad2Deg;
//Debug.Log("타겟과 AI의 각도 : " + theta);
if (theta <= SightAngle) return true;
else return false;
return false;
}
두벡터 사이각도 즉, 자신이보는 시선 방향이랑 자신과 타겟의 방향 사이각도를 구하는것 !
자신이 보는 시선 => Tr.forward
자신과 타겟의 방향 Vector3 targetDir = (AttackTargetPlayer.position - Tr.position).normalized;
내적을 이용하여 두사이각을 알아낸다
A dot B = |A||B|cos@ 이다
cos@ = A dot B / |A||B|
@ = cos^-1(A dot B / |A||B|)
위에 유도된 식으로 @ 각을 알수 있다 ( 참고로 @ 는 라디안 이다)
코사인의 역함수는 아크코사인 이다.
cos^-1 => 코드에서 mathf.Acos 를 활용하면된다.
A dot B 는 Vector3.Dot(a,b) 를 활용하면된다
|A||B| 는 A벡터의 크기, B 벡터의 크기이다.
A = Tr.forward
B = Vector3 targetDir = (AttackTargetPlayer.position - Tr.position).normalized;
Tr.foward 는 오브젝트로컬 기준으로 z방향으 노말벡터를 의미한다
B = Vector3 targetDir 는 적방향의 노말벡터를 의미한다
노말벡터의 크기는 1이기에
| 1 || 1 | = 1 이다
그래서 위 코드에 |A||B|이 생략 되었다. 5/1 = 5 아니겟는가
라디인값인 Mathf.Acos(dot) 는 각도를 구하려면 변환해야한다. 그래서 mathf.Rad2Deg 를 곱해준다
float theta = Mathf.Acos(dot) * Mathf.Rad2Deg;
계산된 theta가 원하는 제한각도 보다 작으면 시야범위안에 있는것이다.
'유니티 > 프로그래밍' 카테고리의 다른 글
[Unity] 오브젝트반투명 처리하기 (0) | 2020.04.09 |
---|---|
[Unity] LayoutUtility.GetPreferredWidth 사용시 주의! (1) | 2020.02.20 |
[Unity] Physics.SyncRigidbodyTransfom 부하시 해결 (0) | 2019.12.06 |
[Unity] 3D 공 계속튕기게 하기 (0) | 2019.10.17 |
[Unity] 유도탄 만들기 (2) | 2019.10.16 |