1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public class TargetCheckTester : MonoBehaviour { private Transform m_transform = null;
[SerializeField] private float m_checkAngle = 60.0f;
[SerializeField] private float m_checkRadius = 6.0f;
[SerializeField] private Transform m_targetTransform = null;
private void CheckTarget1() { if (null == m_targetTransform) return;
Vector3 myPos = m_transform.position; Vector3 myForward = m_transform.forward; float halfAngle = m_checkAngle * 0.5f; Vector3 dirUp = Quaternion.Euler(0.0f, -halfAngle, 0.0f) * myForward; Vector3 dirDown = Quaternion.Euler(0.0f, halfAngle, 0.0f) * myForward;
Vector3 upCheck = Vector3.Cross(myForward, dirUp); Vector3 downCheck = Vector3.Cross(myForward, dirDown);
Vector3 targetPos = m_targetTransform.position; targetPos.y = myPos.y; Vector3 toTargetDir = targetPos - myPos;
Vector3 point1 = myPos + dirUp * m_checkRadius; Vector3 point2 = myPos + dirDown * m_checkRadius; Vector3 point0 = myPos + myForward * m_checkRadius;
Debug.DrawLine(myPos, point1, Color.yellow, Time.deltaTime); Debug.DrawLine(myPos, point2, Color.yellow, Time.deltaTime); Debug.DrawLine(myPos, point0, Color.yellow, Time.deltaTime); Debug.DrawLine(point1, point0, Color.yellow, Time.deltaTime); Debug.DrawLine(point2, point0, Color.yellow, Time.deltaTime); Debug.DrawLine(myPos, targetPos, Color.red, Time.deltaTime);
if (Vector3.Dot(toTargetDir, myForward) < 0.0f || toTargetDir.sqrMagnitude > m_checkRadius * m_checkRadius) return;
Vector3 targetUpCheck = Vector3.Cross(toTargetDir, dirUp); Vector3 targetDownCheck = Vector3.Cross(toTargetDir, dirDown);
float selfCheck = Vector3.Dot(targetUpCheck, targetDownCheck); float dotCheckUp = Vector3.Dot(upCheck, targetUpCheck); float dotCheckDown = Vector3.Dot(targetDownCheck, downCheck); if (selfCheck <= 0.0f && dotCheckUp * dotCheckDown >= 0.0f) { Debug.Log("target in sight"); }
}
#region mono method
private void Awake() { m_transform = this.transform; }
private void Update() { CheckTarget1(); }
#endregion
}
|