Newer
Older
HierarchicalFSM-Unity3D / Assets / Scripts / NPC / FSM / Actions / Patrol / PatrolWalkAction.cs
@Rackday Rackday on 19 Jul 2024 2 KB Project creation
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Unity.VisualScripting;
  4. using UnityEngine;
  5. using UnityEngine.AI;
  6. [CreateAssetMenu(menuName = "Finite State Machine/Action/Patrol/WalkAction")]
  7. public class PatrolWalkAction : Action
  8. {
  9. [SerializeField] private float waitTime = 2f; // Wait time at each waypoint
  10. [SerializeField] private float distOffSet = 0.1f; // Distance offset to determine when the agent has reached the waypoint
  11. [SerializeField] private bool isWaiting = false; // Flag to check if the agent is currently waiting
  12. public override void Execute(FSM fsm)
  13. {
  14. // Required components for the action
  15. NavMeshAgent agent = fsm.Controller.Agent;
  16. Waypoints waypoints = fsm.Controller.Waypoints;
  17. Animator animator = fsm.Controller.Animator;
  18. if (agent == null || waypoints == null)
  19. {
  20. return; // If essential components are missing, exit
  21. }
  22. if (!isWaiting)
  23. {
  24. animator.SetBool("IsMoving", true); // Sets the agent animation to true
  25. fsm.Controller.Agent.isStopped = false; // Agent starts moving
  26. // Check the remaining distance to the destination
  27. if (!agent.pathPending && agent.remainingDistance <= distOffSet)
  28. {
  29. // Generates a random index
  30. int randomIndex = Random.Range(0, waypoints.WaypointsList.Length);
  31. // Sets agent destination to the random position
  32. Vector3 randomPos = waypoints.WaypointsList[randomIndex].transform.position;
  33. agent.SetDestination(randomPos);
  34. Debug.Log($"Moving to waypoint: {randomPos}");
  35. // Start the Coroutine to wait at the waypoint
  36. fsm.StartCoroutine(WaitInWaypoint(fsm));
  37. }
  38. }
  39. }
  40. private IEnumerator WaitInWaypoint(FSM fsm)
  41. {
  42. // Set the agent to stop moving and update the animation
  43. isWaiting = true;
  44. fsm.Controller.Agent.isStopped = true;
  45. fsm.Controller.Animator.SetBool("IsMoving", false);
  46. Debug.Log("Waiting at waypoint");
  47. // Wait for the specified time
  48. yield return new WaitForSeconds(waitTime);
  49. // After waiting, set the agent to move again
  50. isWaiting = false;
  51. }
  52. }