Files
BABA_YAGA/Assets/Scripts/AI NPC/EnemyAI.cs

257 lines
8.4 KiB
C#
Raw Normal View History

2026-06-05 14:10:16 +07:00
using System.Collections;
2026-05-30 17:41:31 +07:00
using System.Collections.Generic;
using UnityEngine;
2026-06-05 15:59:33 +07:00
using UnityEngine.AI;
using System.Linq;
2026-05-30 17:41:31 +07:00
2026-06-05 14:10:16 +07:00
[RequireComponent(typeof(NavMeshAgent))]
[RequireComponent(typeof(Rigidbody))]
2026-06-05 15:59:33 +07:00
[RequireComponent(typeof(FieldOfView))]
2026-05-30 17:41:31 +07:00
public class EnemyAI : MonoBehaviour
{
2026-06-03 13:42:09 +07:00
[Header("References")]
2026-05-30 17:41:31 +07:00
public Transform player;
2026-06-05 15:59:33 +07:00
private NavMeshAgent agent;
private Rigidbody rb;
private FieldOfView fov;
2026-06-03 13:42:09 +07:00
2026-06-05 15:59:33 +07:00
[Header("Movement & Rotation")]
public float moveSpeed = 3f;
public float rotateSpeed = 50f;
2026-06-03 13:42:09 +07:00
2026-06-05 15:59:33 +07:00
[Header("Patrol Waypoints")]
2026-06-05 14:10:16 +07:00
public Transform[] patrolPoints;
2026-06-05 15:59:33 +07:00
public float patrolWaitTime = 2f;
2026-06-05 14:10:16 +07:00
private int currentPatrolIndex = 0;
2026-06-05 15:59:33 +07:00
private float currentWaitTime;
2026-06-04 15:41:01 +07:00
2026-06-05 15:59:33 +07:00
[Header("Artifact State")]
2026-06-03 13:42:09 +07:00
public bool playerHasArtifact;
2026-06-05 15:59:33 +07:00
[Header("Laser Weapon")]
2026-06-03 13:42:09 +07:00
public GameObject laserPrefab;
public Transform firePoint;
public float minShootDelay = 1f;
public float maxShootDelay = 3f;
2026-06-05 15:59:33 +07:00
private float nextShootTime;
2026-06-03 13:42:09 +07:00
2026-06-05 15:59:33 +07:00
[Header("Dodge Settings (Rigidbody)")]
public float dodgeForce = 8f;
public float dodgeDuration = 0.25f;
public float dodgeCooldown = 1.5f;
2026-06-05 14:10:16 +07:00
private bool isDodging = false;
2026-06-05 15:59:33 +07:00
private float nextDodgeTime;
// Gốc của Cây hành vi
2026-05-30 17:41:31 +07:00
public Node behaviorTreeRoot;
2026-06-03 13:42:09 +07:00
private void Start()
2026-05-30 17:41:31 +07:00
{
2026-06-04 15:41:01 +07:00
agent = GetComponent<NavMeshAgent>();
2026-06-05 14:10:16 +07:00
rb = GetComponent<Rigidbody>();
2026-06-05 15:59:33 +07:00
fov = GetComponent<FieldOfView>();
2026-06-04 23:01:39 +07:00
2026-06-05 15:59:33 +07:00
agent.speed = moveSpeed;
2026-06-05 14:10:16 +07:00
2026-06-05 15:59:33 +07:00
// Tự động tìm tất cả điểm PatrolPoint trong Map giống RobotBrain
patrolPoints = GameObject.FindGameObjectsWithTag("PatrolPoint")
.Select(go => go.transform).ToArray();
// Cấu hình Rigidbody để không bị đổ ngã khi va chạm vật lý thông thường
rb.isKinematic = true;
rb.freezeRotation = true;
FindPlayer();
2026-05-30 17:41:31 +07:00
InitBehaviorTree();
}
2026-06-03 13:42:09 +07:00
private void Update()
2026-05-30 17:41:31 +07:00
{
2026-06-05 14:10:16 +07:00
if (player == null) FindPlayer();
2026-06-05 15:59:33 +07:00
// Thực thi cây hành vi liên tục mỗi khung hình
2026-06-03 13:42:09 +07:00
behaviorTreeRoot?.Evaluate();
2026-05-30 17:41:31 +07:00
}
2026-06-04 15:41:01 +07:00
private void FindPlayer()
{
GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
2026-06-05 14:10:16 +07:00
if (playerObj != null) player = playerObj.transform;
}
2026-06-03 13:42:09 +07:00
private void InitBehaviorTree()
2026-05-30 17:41:31 +07:00
{
2026-06-05 15:59:33 +07:00
// Ưu tiên số 1: Kiểm tra và thực hiện né đòn
var dodgeNode = new TaskNode(CheckAndActionDodge);
// Ưu tiên số 2: Có cổ vật -> Đứng lại tập trung bắn hạ
2026-06-03 13:42:09 +07:00
var laserSequence = new Sequence(new List<Node>
{
new TaskNode(CheckHasArtifact),
new TaskNode(ActionFocusAndShoot)
});
2026-06-05 15:59:33 +07:00
// Ưu tiên số 3: Tương tác tầm nhìn (Đuổi theo hoặc Đi kiểm tra vết tích)
var trackingSelector = new Selector(new List<Node>
2026-06-05 14:10:16 +07:00
{
2026-06-05 15:59:33 +07:00
// Nhìn thấy trực tiếp -> dí theo
new Sequence(new List<Node> { new TaskNode(CheckCanSeePlayer), new TaskNode(ActionChasePlayer) }),
// Mất dấu -> đi đến vị trí cuối cùng để điều tra
new Sequence(new List<Node> { new TaskNode(CheckHasInvestigateTarget), new TaskNode(ActionInvestigate) })
2026-06-05 14:10:16 +07:00
});
2026-06-05 15:59:33 +07:00
// Ưu tiên số 4: Mặc định đi tuần tra vòng quanh Map
2026-06-04 15:41:01 +07:00
var patrolNode = new TaskNode(ActionPatrol);
2026-06-03 13:42:09 +07:00
2026-06-05 15:59:33 +07:00
// Tạo cây tổng hợp theo thứ tự ưu tiên từ trên xuống dưới
2026-05-30 17:41:31 +07:00
behaviorTreeRoot = new Selector(new List<Node>
{
2026-06-05 15:59:33 +07:00
dodgeNode,
2026-06-03 13:42:09 +07:00
laserSequence,
2026-06-05 15:59:33 +07:00
trackingSelector,
2026-06-04 15:41:01 +07:00
patrolNode
2026-05-30 17:41:31 +07:00
});
}
2026-06-05 15:59:33 +07:00
#region CONDITIONS & COMPOSITE NODES
private NodeState CheckAndActionDodge()
{
if (isDodging) return NodeState.Running;
// ĐIỀU KIỆN NÉ: Phải nhìn thấy Player VÀ Player nhấn chuột trái VÀ hết cooldown né
if (fov.canSeePlayer && Input.GetMouseButtonDown(0) && Time.time >= nextDodgeTime)
{
StartCoroutine(DodgeRollRoutine());
nextDodgeTime = Time.time + dodgeCooldown;
return NodeState.Running;
}
return NodeState.Failure;
}
2026-06-03 13:42:09 +07:00
private NodeState CheckHasArtifact()
{
2026-06-04 15:41:01 +07:00
return playerHasArtifact ? NodeState.Success : NodeState.Failure;
2026-06-03 13:42:09 +07:00
}
private NodeState CheckCanSeePlayer()
{
2026-06-05 15:59:33 +07:00
return fov.canSeePlayer ? NodeState.Success : NodeState.Failure;
2026-06-05 14:10:16 +07:00
}
2026-06-03 13:42:09 +07:00
2026-06-05 15:59:33 +07:00
private NodeState CheckHasInvestigateTarget()
2026-06-05 14:10:16 +07:00
{
2026-06-05 15:59:33 +07:00
return fov.lastKnownPlayerPosition != Vector3.zero ? NodeState.Success : NodeState.Failure;
2026-06-03 13:42:09 +07:00
}
#endregion
#region ACTIONS
2026-06-05 15:59:33 +07:00
// Coroutine xử lý né bằng lực đẩy Rigidbody một cách thực tế
private IEnumerator DodgeRollRoutine()
{
isDodging = true;
agent.enabled = false; // Tắt định vị NavMesh để nhường quyền cho Vật lý
rb.isKinematic = false; // Bật chế độ vật lý động để nhận lực lực đẩy
// Tính toán hướng né: Vuông góc với hướng nhìn của Player (Tránh sang trái hoặc phải)
Vector3 directionToPlayer = (player.position - transform.position).normalized;
Vector3 perpendicularDir = new Vector3(-directionToPlayer.z, 0, directionToPlayer.x);
// Chọn ngẫu nhiên trái hoặc phải
Vector3 dodgeDirection = (Random.Range(0, 2) == 0 ? perpendicularDir : -perpendicularDir).normalized;
// Tác dụng lực đẩy Impulse tức thì
rb.AddForce(dodgeDirection * dodgeForce, ForceMode.Impulse);
yield return new WaitForSeconds(dodgeDuration);
// Kết thúc né: Trả lại quyền điều khiển cho NavMeshAgent
rb.linearVelocity = Vector3.zero; // Cú pháp chuẩn của Unity 6 (thay cho rb.velocity)
rb.isKinematic = true;
agent.enabled = true;
isDodging = false;
}
private NodeState ActionPatrol()
2026-05-30 17:41:31 +07:00
{
2026-06-05 14:10:16 +07:00
if (patrolPoints.Length == 0) return NodeState.Failure;
2026-06-04 21:26:19 +07:00
2026-06-05 14:10:16 +07:00
Debug.Log("Patrolling...");
agent.isStopped = false;
2026-06-05 15:59:33 +07:00
agent.speed = moveSpeed * 0.6f; // Đi tuần tra chậm rãi quay theo hướng đi tự động của NavMesh
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
agent.SetDestination(patrolPoints[currentPatrolIndex].position);
2026-06-04 15:41:01 +07:00
2026-06-05 15:59:33 +07:00
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance)
2026-06-05 14:10:16 +07:00
{
2026-06-05 15:59:33 +07:00
currentWaitTime += Time.deltaTime;
if (currentWaitTime >= patrolWaitTime)
{
currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length;
currentWaitTime = 0f;
}
2026-06-04 15:41:01 +07:00
}
2026-05-30 17:41:31 +07:00
return NodeState.Running;
}
2026-06-05 15:59:33 +07:00
private NodeState ActionChasePlayer()
2026-05-30 17:41:31 +07:00
{
2026-06-05 15:59:33 +07:00
Debug.Log("Chasing Player!");
2026-06-05 14:10:16 +07:00
agent.isStopped = false;
2026-06-05 15:59:33 +07:00
agent.speed = moveSpeed; // Chạy nhanh hết tốc lực
2026-06-05 14:10:16 +07:00
agent.SetDestination(player.position);
2026-06-04 23:01:39 +07:00
2026-06-05 14:10:16 +07:00
return NodeState.Running;
}
2026-06-04 21:26:19 +07:00
2026-06-05 14:10:16 +07:00
private NodeState ActionInvestigate()
{
2026-06-05 15:59:33 +07:00
Debug.Log("Investigating Last Position...");
2026-06-04 15:41:01 +07:00
agent.isStopped = false;
2026-06-05 15:59:33 +07:00
agent.speed = moveSpeed * 0.8f;
agent.SetDestination(fov.lastKnownPlayerPosition);
2026-06-05 14:10:16 +07:00
2026-06-05 15:59:33 +07:00
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance)
2026-06-05 14:10:16 +07:00
{
2026-06-05 15:59:33 +07:00
// Đến nơi rồi mà không thấy ai, xóa vị trí cuối cùng để quay lại tuần tra
fov.lastKnownPlayerPosition = Vector3.zero;
return NodeState.Success;
2026-06-05 14:10:16 +07:00
}
2026-05-30 17:41:31 +07:00
return NodeState.Running;
}
2026-06-03 13:42:09 +07:00
private NodeState ActionFocusAndShoot()
2026-05-30 17:41:31 +07:00
{
2026-06-05 15:59:33 +07:00
Debug.Log("Focus and Shoot!");
agent.isStopped = true; // Dừng di chuyển để đứng ngắm bắn cố định
2026-06-04 21:26:19 +07:00
2026-06-05 15:59:33 +07:00
// Tự xoay người hướng thẳng về phía Player
2026-06-04 15:41:01 +07:00
Vector3 dir = player.position - transform.position;
2026-06-03 13:42:09 +07:00
dir.y = 0f;
if (dir != Vector3.zero)
{
2026-06-04 15:41:01 +07:00
Quaternion targetRotation = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotateSpeed * Time.deltaTime);
2026-05-30 17:41:31 +07:00
}
2026-06-03 13:42:09 +07:00
2026-06-05 15:59:33 +07:00
// Đếm ngược thời gian bắn ngẫu nhiên
2026-06-03 13:42:09 +07:00
if (Time.time >= nextShootTime)
2026-05-30 17:41:31 +07:00
{
2026-06-03 13:42:09 +07:00
ShootLaser();
2026-06-04 15:41:01 +07:00
nextShootTime = Time.time + Random.Range(minShootDelay, maxShootDelay);
2026-05-30 17:41:31 +07:00
}
2026-06-03 13:42:09 +07:00
return NodeState.Running;
2026-05-30 17:41:31 +07:00
}
2026-06-03 13:42:09 +07:00
private void ShootLaser()
{
2026-06-04 15:41:01 +07:00
if (laserPrefab == null || firePoint == null) return;
Instantiate(laserPrefab, firePoint.position, firePoint.rotation);
2026-06-05 14:10:16 +07:00
}
#endregion
2026-06-05 15:59:33 +07:00
}