Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / NPC / FOV.cs
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class FOV : MonoBehaviour
{
    [Header("FOV Settings: ")]
    [SerializeField] private float fovRadius;
    [Range(0, 360)][SerializeField] private float angle;
    [SerializeField] private float fovDelay;
    [SerializeField] private LayerMask targetMask;

    [SerializeField] private GameObject target;

    private NPCConroller controller;

    public float Radius => fovRadius;
    public float Angle => angle;
    public NPCConroller Controller => controller;
    private bool isEnabled = true;

    public bool IsEnabled { get => isEnabled; set => isEnabled = value; }

    private void Awake()
    {
        controller = GetComponent<NPCConroller>();
        isEnabled = true;
    }
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(FOVRoutine(fovDelay));
    }

    private void OnEnable()
    {
        StartCoroutine(FOVRoutine(fovDelay));
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void PerformFov()
    {
        if (target == null && isEnabled)
        {
            Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, fovRadius, targetMask);

            if (colliders.Length != 0)
            {
                foreach (Collider2D collider in colliders)
                {
                    GameObject potentialTarget = collider.gameObject;
                    Vector2 dirToTarget = (potentialTarget.transform.position - transform.position).normalized;

                    // Check if the target is within the specified angle
                    if (Vector2.Angle(transform.right, dirToTarget) < angle / 2)
                    {
                        target = potentialTarget;
                        Debug.Log("Target detected within angle!");
                        return; // Exit after finding the first valid target
                    }
                }
            }
        }
    }

    private IEnumerator FOVRoutine(float seconds)
    {
        while (true)
        {
            WaitForSeconds wait = new WaitForSeconds(seconds);
            yield return wait;
            PerformFov();
        }
    }

    public GameObject GetTarget() => target;
    public void ClearTarget() => target = null;
}