DonutDonkey_U_MultimediaApplication_Fps/Assets/Script/Mono/Actors/FOV/FieldOfView.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Script.Mono.Actors.FOV
{
    public class FieldOfView : MonoBehaviour
    {

        private float view_radius;
        public float viewRadius { get => view_radius; }
        
        private float view_angle;
        public float viewAngle { get => view_angle; }

        public LayerMask targetMask;
        public LayerMask obstacleMask;

        [HideInInspector]
        public List<Transform> visibleTargets = new List<Transform>();

        void Start() {
            StartCoroutine ("FindTargetsWithDelay", .2f);
            view_angle = GetComponent<Enemy>().DActor.FOV;
            view_radius = GetComponent<Enemy>().DActor.viewRadius;
        }


        IEnumerator FindTargetsWithDelay(float delay) {
            while (true) {
                yield return new WaitForSeconds (delay);
                FindVisibleTargets ();
            }
        }

        void FindVisibleTargets() {
            visibleTargets.Clear ();
            Collider[] targetsInViewRadius = Physics.OverlapSphere (transform.position, viewRadius, targetMask);

            for (int i = 0; i < targetsInViewRadius.Length; i++) {
                Transform target = targetsInViewRadius [i].transform;
                Vector3 dirToTarget = (target.position - transform.position).normalized;
                if (Vector3.Angle (transform.forward, dirToTarget) < viewAngle / 2) {
                    float dstToTarget = Vector3.Distance (transform.position, target.position);

                    if (!Physics.Raycast (transform.position, dirToTarget, dstToTarget, obstacleMask)) {
                        visibleTargets.Add (target);
                    }
                }
            }
        }


        public Vector3 DirFromAngle(float angleInDegrees, bool angleIsGlobal) {
            if (!angleIsGlobal) {
                angleInDegrees += transform.eulerAngles.y;
            }
            return new Vector3(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad),0,Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));
        }
    }
}