This commit is contained in:
2026-06-04 23:01:39 +07:00
parent 45d3fe8c21
commit 67910bf6c8
68 changed files with 5978 additions and 404 deletions

View File

@@ -1,6 +1,7 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI; // Cần thiết để dùng NavMesh
using Hallucinate.Audio;
[RequireComponent(typeof(NavMeshAgent))] // Tự động thêm component này nếu chưa có
public class EnemyAI : MonoBehaviour
@@ -28,6 +29,11 @@ public class EnemyAI : MonoBehaviour
public float minShootDelay = 1f;
public float maxShootDelay = 3f;
[Header("Audio")]
public string alertSound = "Enemy_Alert";
public string shootSound = "Enemy_Shoot";
private bool hasSpottedPlayer; // Để chỉ kêu alert 1 lần
private float nextShootTime;
private NavMeshAgent agent;
@@ -37,10 +43,10 @@ public class EnemyAI : MonoBehaviour
{
agent = GetComponent<NavMeshAgent>();
agent.speed = moveSpeed;
// Lưu lại vị trí ban đầu để làm tâm của khu vực tuần tra
startPosition = transform.position;
nextShootTime = Time.time + Random.Range(minShootDelay, maxShootDelay);
InitBehaviorTree();
FindPlayer();
@@ -109,9 +115,15 @@ public class EnemyAI : MonoBehaviour
if (distance <= detectRange)
{
if (!hasSpottedPlayer)
{
hasSpottedPlayer = true;
AudioManager.Instance?.Play(alertSound, position: transform.position);
}
return NodeState.Success;
}
hasSpottedPlayer = false; // Reset nếu player ra khỏi tầm mắt
return NodeState.Failure;
}
@@ -139,7 +151,7 @@ public class EnemyAI : MonoBehaviour
Vector3 randomDirection = Random.insideUnitSphere * patrolRadius;
randomDirection += startPosition;
NavMeshHit hit;
// Đảm bảo điểm ngẫu nhiên nằm trên bề mặt NavMesh hợp lệ
if (NavMesh.SamplePosition(randomDirection, out hit, patrolRadius, 1))
{
@@ -157,7 +169,7 @@ public class EnemyAI : MonoBehaviour
if (player == null) return NodeState.Failure;
// Debug.Log("Chasing Player");
if (!agent.isActiveAndEnabled || !agent.isOnNavMesh) return NodeState.Failure;
agent.isStopped = false;
@@ -172,7 +184,7 @@ public class EnemyAI : MonoBehaviour
if (player == null) return NodeState.Failure;
// Debug.Log("Focus and Shoot!");
if (!agent.isActiveAndEnabled || !agent.isOnNavMesh) return NodeState.Failure;
// Dừng NavMeshAgent lại để đứng bắn, tránh bị trượt
@@ -202,6 +214,7 @@ public class EnemyAI : MonoBehaviour
{
if (laserPrefab == null || firePoint == null) return;
Instantiate(laserPrefab, firePoint.position, firePoint.rotation);
AudioManager.Instance?.Play(shootSound, position: transform.position);
// Debug.Log("Laser Shot!");
}