Newer
Older
HierarchicalFSM-Unity3D / Assets / Scripts / NPC / FSM / Actions / Combat / Ranged / Cover / EnableCoverAction.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

[CreateAssetMenu(menuName = "Finite State Machine/Action/Combat/Ranged/Cover/GetCover")]
public class EnableCoverAction : Action
{
    [SerializeField] private float maxDistanceRay = 0.2f;

    public override void Execute(FSM fsm)
    {
        Animator animator = fsm.Controller.Animator;
        RangedCombatState parentState = (RangedCombatState)fsm.CurrentState().GetParentState();
        GameObject coverSpot = null;

        if (parentState is RangedCombatState)
        {
            coverSpot = parentState.coverObject;
        }

        else
        {
            coverSpot = null;
            Debug.LogError($"The Parent State is not the type: {nameof(RangedCombatState)}!");
        }

        //Enables the cover action animation
        //If the target is close enough of the cover location
        if(!animator.GetBool("CoverState") && coverSpot != null)
        {
            RaycastHit hit;
            Vector3 direction = (coverSpot.transform.position - fsm.transform.position).normalized;
            Vector3 agentPos = new Vector3(fsm.transform.position.x, fsm.transform.position.y + 1f, fsm.transform.position.z);
            Ray ray = new Ray(agentPos, direction);
            Debug.DrawRay(agentPos, direction * 10f, Color.green);
            //Performs a raycast to know the distance to the cover spot
            if (Physics.Raycast(ray, out hit, maxDistanceRay))
            {
                if (hit.transform != null)
                {
                    fsm.Controller.Animator.SetBool("CoverState", true);
                }
            }

            else
            {
                Debug.LogWarning("Raycast didn't hit nothing!");
            }
        }
    }
}