ambrose01

EnemyAI.cs

Oct 21st, 2025
1,473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.67 KB | Source Code | 0 0
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3.  
  4. public class EnemyAI : MonoBehaviour
  5. {
  6.     [Header("References")]
  7.     public Transform player;
  8.     public Animator animator;
  9.     public PlayerHealth playerHealth;
  10.  
  11.     [Header("Settings")]
  12.     public float detectionRadius = 15f;
  13.     public float attackRange = 2f;
  14.     public float patrolRadius = 20f;
  15.     public float attackCooldown = 2f;
  16.     public float patrolIdleTime = 3f;
  17.     public float rotationSpeed = 7f;
  18.     public float attackDuration = 1.0f; // Duration of attack animation
  19.  
  20.     private NavMeshAgent agent;
  21.     private float cooldownTimer;
  22.     private float idleTimer;
  23.     private float attackTimer;
  24.  
  25.     private Vector3 patrolPoint;
  26.     private bool isPatrolling;
  27.     private bool isIdle;
  28.     private bool isAttacking;
  29.  
  30.     private enum State { Patrol, Chase, Attack }
  31.     private State currentState;
  32.  
  33.     void Start()
  34.     {
  35.         agent = GetComponent<NavMeshAgent>();
  36.         if (animator == null) animator = GetComponent<Animator>();
  37.         if (playerHealth == null && player != null) playerHealth = player.GetComponent<PlayerHealth>();
  38.  
  39.         SetNewPatrolPoint();
  40.         currentState = State.Patrol;
  41.     }
  42.  
  43.     void Update()
  44.     {
  45.         cooldownTimer -= Time.deltaTime;
  46.  
  47.         float distanceToPlayer = Vector3.Distance(transform.position, player.position);
  48.  
  49.         // Cancel attack if player leaves attack range
  50.         if (isAttacking && distanceToPlayer > attackRange)
  51.         {
  52.             CancelAttack();
  53.             currentState = State.Chase;
  54.         }
  55.  
  56.         // Handle attack duration manually (no animation event needed)
  57.         if (isAttacking)
  58.         {
  59.             attackTimer -= Time.deltaTime;
  60.             if (attackTimer <= 0f)
  61.             {
  62.                 EndAttack();
  63.             }
  64.         }
  65.  
  66.         // State switching
  67.         if (!isAttacking)
  68.         {
  69.             if (distanceToPlayer <= attackRange && cooldownTimer <= 0f)
  70.                 currentState = State.Attack;
  71.             else if (distanceToPlayer <= detectionRadius)
  72.                 currentState = State.Chase;
  73.             else
  74.                 currentState = State.Patrol;
  75.         }
  76.  
  77.         // Execute state
  78.         switch (currentState)
  79.         {
  80.             case State.Patrol: Patrol(); break;
  81.             case State.Chase: ChasePlayer(); break;
  82.             case State.Attack: Attack(); break;
  83.         }
  84.  
  85.         animator.SetBool("isWalking", agent.velocity.magnitude > 0.1f && !isAttacking);
  86.  
  87.         if (!isAttacking)
  88.             RotateTowardsMovementDirection();
  89.     }
  90.  
  91.     void Patrol()
  92.     {
  93.         if (isIdle)
  94.         {
  95.             idleTimer += Time.deltaTime;
  96.             if (idleTimer >= patrolIdleTime)
  97.             {
  98.                 SetNewPatrolPoint();
  99.                 idleTimer = 0f;
  100.             }
  101.             return;
  102.         }
  103.  
  104.         if (!isPatrolling || Vector3.Distance(transform.position, patrolPoint) < 1.5f)
  105.         {
  106.             isIdle = true;
  107.             isPatrolling = false;
  108.             agent.ResetPath();
  109.         }
  110.     }
  111.  
  112.     void SetNewPatrolPoint()
  113.     {
  114.         Vector3 randomDirection = Random.insideUnitSphere * patrolRadius + transform.position;
  115.  
  116.         if (NavMesh.SamplePosition(randomDirection, out NavMeshHit hit, patrolRadius, NavMesh.AllAreas))
  117.         {
  118.             patrolPoint = hit.position;
  119.             agent.SetDestination(patrolPoint);
  120.             isPatrolling = true;
  121.             isIdle = false;
  122.         }
  123.     }
  124.  
  125.     void ChasePlayer()
  126.     {
  127.         isIdle = false;
  128.         isPatrolling = false;
  129.  
  130.         if (agent.isOnNavMesh && player != null)
  131.             agent.SetDestination(player.position);
  132.     }
  133.  
  134.     void Attack()
  135.     {
  136.         if (isAttacking) return;
  137.  
  138.         float distance = Vector3.Distance(transform.position, player.position);
  139.         if (distance > attackRange)
  140.         {
  141.             currentState = State.Chase;
  142.             return;
  143.         }
  144.  
  145.         isAttacking = true;
  146.         cooldownTimer = attackCooldown;
  147.         attackTimer = attackDuration;
  148.         agent.ResetPath();
  149.  
  150.         // Rotate to face player instantly
  151.         Vector3 lookPos = new Vector3(player.position.x, transform.position.y, player.position.z);
  152.         transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookPos - transform.position), Time.deltaTime * rotationSpeed);
  153.  
  154.         animator.ResetTrigger("Attack");
  155.         animator.SetTrigger("Attack");
  156.     }
  157.  
  158.     public void DealDamage()
  159.     {
  160.         if (Vector3.Distance(transform.position, player.position) <= attackRange)
  161.         {
  162.             playerHealth.TakeDamage(10); // Damage amount
  163.         }
  164.     }
  165.  
  166.     public void EndAttack()
  167.     {
  168.         isAttacking = false;
  169.         attackTimer = 0f;
  170.     }
  171.  
  172.     public void CancelAttack()
  173.     {
  174.         if (!isAttacking) return;
  175.  
  176.         isAttacking = false;
  177.         attackTimer = 0f;
  178.         cooldownTimer = attackCooldown;
  179.  
  180.         animator.ResetTrigger("Attack");
  181.  
  182.         // Instantly cut the attack animation
  183.         if (animator.HasState(0, Animator.StringToHash("Walk")))
  184.             animator.CrossFade("Walk", 0.1f);
  185.         else if (animator.HasState(0, Animator.StringToHash("Walk")))
  186.             animator.CrossFade("Walk", 0.1f);
  187.  
  188.         if (agent.isOnNavMesh && player != null)
  189.             agent.SetDestination(player.position);
  190.     }
  191.  
  192.     void RotateTowardsMovementDirection()
  193.     {
  194.         if (agent.velocity.sqrMagnitude > 0.1f)
  195.         {
  196.             Quaternion targetRotation = Quaternion.LookRotation(agent.velocity.normalized);
  197.             transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
  198.         }
  199.     }
  200. }
  201.  
Tags: Free roam AI
Advertisement
Add Comment
Please, Sign In to add comment