Newer
Older
TheVengeance-Project-IADE-Unity2D / Assets / Scripts / NPC / FOV.cs
using System.Collections;
using System.Collections.Generic;
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 LayerMask obstructionMask;

    [SerializeField] private GameObject target;

    private NPCConroller controller;
    private Agent agent;

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

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

    private void PerformFov()
    {
        Collider2D collider = Physics2D.OverlapCircle(transform.position, fovRadius, targetMask);
        GameObject potentialTarget = null;

        if (collider != null)
        {
            potentialTarget = collider.gameObject;
            Debug.Log($"Collider FOV detected something: {potentialTarget}");
            Vector2 dirToTarget = (Vec3ToVec2(potentialTarget.transform.position) - Vec3ToVec2(transform.position)).normalized;
            if (Vector3.Angle(transform.forward, dirToTarget) < Angle/2)
            {
                Debug.Log("Target in Angle!");
                target = potentialTarget;
                //float distanceToTarget = Vector2.Distance(transform.forward, dirToTarget);

                //if(Physics2D.Raycast(transform.position, dirToTarget, distanceToTarget,))
            }
        }
    }

    private static Vector2 Vec3ToVec2(Vector3 vec) => (Vector2)vec;

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

    public GameObject GetTarget() => target;
}