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

375 lines
12 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 16:00:04 +07:00
[Header("Conversation")]
public string npcName = "Guard";
public string persona = "You are a grumpy guard protecting gold.";
public float talkRange = 4f;
public float talkCooldown = 30f;
private float lastTalkTime;
private bool isTalking;
private EnemyAI talkingPartner;
private Hallucinate.UI.ChatBubble chatBubble;
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-05 16:00:04 +07:00
chatBubble = GetComponentInChildren<Hallucinate.UI.ChatBubble>(true);
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
// Tự động tìm tất cả điểm PatrolPoint trong Map
2026-06-05 15:59:33 +07:00
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) }),
2026-06-05 15:59:33 +07:00
// 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
});
// Ưu tiên số 4: Gần NPC khác -> nói chuyện (Mới)
2026-06-05 16:00:04 +07:00
var talkSequence = new Sequence(new List<Node>
{
new TaskNode(CheckCanTalkToNPC),
new TaskNode(ActionTalk)
});
// Ưu tiên số 5: 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-05 16:00:04 +07:00
talkSequence,
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
2026-06-05 16:00:04 +07:00
private NodeState CheckCanTalkToNPC()
{
if (playerHasArtifact || fov.canSeePlayer) return NodeState.Failure;
2026-06-05 16:00:04 +07:00
if (Time.time < lastTalkTime + talkCooldown) return NodeState.Failure;
if (isTalking) return NodeState.Success;
// Tìm NPC gần nhất
Collider[] hitColliders = Physics.OverlapSphere(transform.position, talkRange);
foreach (var hit in hitColliders)
{
if (hit.gameObject != gameObject && hit.CompareTag("Enemy"))
{
EnemyAI other = hit.GetComponent<EnemyAI>();
if (other != null && !other.isTalking && Time.time >= other.lastTalkTime + talkCooldown)
{
talkingPartner = other;
return NodeState.Success;
}
}
}
return NodeState.Failure;
}
2026-06-03 13:42:09 +07:00
private NodeState CheckHasArtifact()
{
2026-06-05 16:00:04 +07:00
if (playerHasArtifact) StopConversation();
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()
{
if (fov.canSeePlayer) StopConversation();
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;
}
2026-06-04 15:41:01 +07:00
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-03 13:42:09 +07:00
}
2026-06-05 16:00:04 +07:00
private NodeState ActionTalk()
{
if (talkingPartner == null) return NodeState.Failure;
if (!isTalking)
{
isTalking = true;
agent.isStopped = true;
// Xoay về phía bạn
FaceTarget(talkingPartner.transform.position);
// Bắt đầu hội thoại qua Gemini
StartNPCConversation();
}
return NodeState.Running;
}
private void StartNPCConversation()
{
string prompt = $"You are {npcName}. You are talking to your fellow guard {talkingPartner.npcName}. " +
"Keep it short (1 sentence). Topic: gold security or complaining about work.";
Hallucinate.AI.GeminiService.Instance.GetResponse(persona, prompt, (response) => {
if (chatBubble != null) chatBubble.Show(response);
// Hẹn giờ kết thúc hội thoại
Invoke(nameof(EndConversation), 5f);
});
// Thông báo cho bạn diễn cũng dừng lại để "nghe"
talkingPartner.OnPartnerTalked(this);
}
public void OnPartnerTalked(EnemyAI partner)
{
isTalking = true;
talkingPartner = partner;
agent.isStopped = true;
FaceTarget(partner.transform.position);
// Chờ bạn nói xong mới phản hồi
Invoke(nameof(EndConversation), 6f);
}
private void EndConversation()
{
isTalking = false;
lastTalkTime = Time.time;
if (agent != null) agent.isStopped = false;
talkingPartner = null;
}
private void StopConversation()
{
if (!isTalking) return;
CancelInvoke(nameof(EndConversation));
EndConversation();
if (chatBubble != null) chatBubble.Show("Suỵt! Có gì đó không ổn...", 2f);
}
private void FaceTarget(Vector3 targetPos)
{
Vector3 dir = targetPos - transform.position;
dir.y = 0;
if (dir != Vector3.zero)
{
transform.rotation = Quaternion.LookRotation(dir);
}
}
2026-06-03 13:42:09 +07:00
#endregion
2026-06-05 15:59:33 +07:00
}