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

326 lines
10 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;
2026-06-05 14:10:16 +07:00
using System.Linq;
2026-05-30 17:41:31 +07:00
using UnityEngine;
2026-06-05 14:10:16 +07:00
using UnityEngine.AI;
2026-05-30 17:41:31 +07:00
2026-06-05 14:10:16 +07:00
[RequireComponent(typeof(NavMeshAgent))]
[RequireComponent(typeof(Rigidbody))]
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-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
[Header("Field of View")]
[Range(0, 360)] public float viewAngle = 90f;
public float viewRadius = 20f;
public LayerMask targetLayerMask; // Gán layer của Player
public LayerMask obstacleLayerMask; // Gán layer của Tường, chướng ngại vật
private bool canSeePlayer = false;
private Vector3 lastKnownPlayerPosition;
private bool isInvestigating = false;
2026-06-03 13:42:09 +07:00
2026-06-04 15:41:01 +07:00
[Header("Patrol Area")]
2026-06-05 14:10:16 +07:00
public Transform[] patrolPoints;
private int currentPatrolIndex = 0;
public float moveSpeed = 3f;
public float chaseSpeed = 5f;
2026-06-04 15:41:01 +07:00
2026-06-03 13:42:09 +07:00
[Header("Artifact")]
public bool playerHasArtifact;
[Header("Laser")]
public GameObject laserPrefab;
public Transform firePoint;
public float minShootDelay = 1f;
public float maxShootDelay = 3f;
2026-06-05 14:10:16 +07:00
public float rotateSpeed = 50f;
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
[Header("Dodge Mechanics")]
public float dodgeForce = 8f; // Lực đẩy văng đi
public float dodgeDuration = 0.5f; // Thời gian nhào lộn/né
public float dodgeCooldown = 3f; // Thời gian chờ giữa 2 lần né
private float nextDodgeTime;
private bool isDodging = false;
private Rigidbody rb;
2026-06-03 13:42:09 +07:00
private float nextShootTime;
2026-06-04 15:41:01 +07:00
private NavMeshAgent agent;
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>();
// Tự động tìm các điểm tuần tra nếu chưa gán
if (patrolPoints == null || patrolPoints.Length == 0)
{
patrolPoints = GameObject.FindGameObjectsWithTag("PatrolPoint")
.Select(go => go.transform).ToArray();
}
2026-06-04 23:01:39 +07:00
2026-06-03 13:42:09 +07:00
nextShootTime = Time.time + Random.Range(minShootDelay, maxShootDelay);
2026-06-05 14:10:16 +07:00
2026-05-30 17:41:31 +07:00
InitBehaviorTree();
2026-06-05 14:10:16 +07:00
StartCoroutine(FindTargetWithDelay(0.1f)); // Chạy FOV quét mục tiêu
2026-05-30 17:41:31 +07:00
}
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();
if (Input.GetMouseButtonDown(0) && canSeePlayer && !isDodging && Time.time >= nextDodgeTime)
2026-06-04 15:41:01 +07:00
{
2026-06-05 14:10:16 +07:00
StartCoroutine(DodgeRoutine());
2026-06-04 15:41:01 +07:00
}
2026-06-05 14:10:16 +07:00
if (isDodging) return;
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;
}
// Coroutine tối ưu việc quét mục tiêu
private IEnumerator FindTargetWithDelay(float delay)
{
while (true)
{
yield return new WaitForSeconds(delay);
FindVisibleTargets();
}
}
private void FindVisibleTargets()
{
canSeePlayer = false;
Collider[] colliders = Physics.OverlapSphere(transform.position, viewRadius, targetLayerMask);
foreach (var col in colliders)
2026-06-04 15:41:01 +07:00
{
2026-06-05 14:10:16 +07:00
Transform target = col.transform;
Vector3 direction = (target.position - transform.position).normalized;
float angle = Vector3.Angle(transform.forward, direction);
// Nếu nằm trong góc nhìn
if (angle < viewAngle / 2)
{
float distanceToTarget = Vector3.Distance(transform.position, target.position);
// Nếu không có vật cản che khuất
if (!Physics.Raycast(transform.position, direction, distanceToTarget, obstacleLayerMask))
{
canSeePlayer = true;
isInvestigating = true;
lastKnownPlayerPosition = target.position;
Debug.DrawLine(transform.position, target.position, Color.blue, 0.1f);
break; // Thấy player rồi thì dừng vòng lặp
}
}
2026-06-04 15:41:01 +07:00
}
}
2026-06-03 13:42:09 +07:00
private void InitBehaviorTree()
2026-05-30 17:41:31 +07:00
{
2026-06-05 14:10:16 +07:00
// 1. Cầm Artifact -> Đứng bắn
2026-06-03 13:42:09 +07:00
var laserSequence = new Sequence(new List<Node>
{
new TaskNode(CheckHasArtifact),
new TaskNode(ActionFocusAndShoot)
});
2026-06-05 14:10:16 +07:00
// 2. Thấy Player -> Đuổi theo
2026-05-30 17:41:31 +07:00
var chaseSequence = new Sequence(new List<Node>
{
new TaskNode(CheckCanSeePlayer),
new TaskNode(ActionMoveToPlayer)
});
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
// 3. Mất dấu Player -> Đi tới vị trí cuối cùng để điều tra
var investigateSequence = new Sequence(new List<Node>
{
new TaskNode(CheckShouldInvestigate),
new TaskNode(ActionInvestigate)
});
// 4. Không có gì -> Tuần tra theo điểm
2026-06-04 15:41:01 +07:00
var patrolNode = new TaskNode(ActionPatrol);
2026-06-03 13:42:09 +07:00
2026-05-30 17:41:31 +07:00
behaviorTreeRoot = new Selector(new List<Node>
{
2026-06-03 13:42:09 +07:00
laserSequence,
2026-05-30 17:41:31 +07:00
chaseSequence,
2026-06-05 14:10:16 +07:00
investigateSequence,
2026-06-04 15:41:01 +07:00
patrolNode
2026-05-30 17:41:31 +07:00
});
}
2026-06-03 13:42:09 +07:00
#region CONDITIONS
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 14:10:16 +07:00
return canSeePlayer ? NodeState.Success : NodeState.Failure;
}
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
private NodeState CheckShouldInvestigate()
{
return isInvestigating ? NodeState.Success : NodeState.Failure;
2026-06-03 13:42:09 +07:00
}
#endregion
#region ACTIONS
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;
agent.speed = moveSpeed;
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
// Đi tới điểm tuần tra hiện tại
agent.SetDestination(patrolPoints[currentPatrolIndex].position);
2026-06-04 15:41:01 +07:00
2026-06-05 14:10:16 +07:00
// Nếu đã tới nơi, chuyển sang điểm tiếp theo
if (agent.remainingDistance <= agent.stoppingDistance && !agent.pathPending)
{
currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length;
2026-06-04 15:41:01 +07:00
}
2026-06-03 13:42:09 +07:00
2026-05-30 17:41:31 +07:00
return NodeState.Running;
}
private NodeState ActionMoveToPlayer()
{
2026-06-04 15:41:01 +07:00
if (player == null) return NodeState.Failure;
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
Debug.Log("Chasing Player...");
agent.isStopped = false;
agent.speed = chaseSpeed;
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()
{
Debug.Log("Investigating last known position...");
2026-06-04 15:41:01 +07:00
agent.isStopped = false;
2026-06-05 14:10:16 +07:00
agent.speed = moveSpeed;
agent.SetDestination(lastKnownPlayerPosition);
// Nếu đi tới nơi mà vẫn không thấy player -> Hủy điều tra, quay về tuần tra
if (agent.remainingDistance <= agent.stoppingDistance && !agent.pathPending)
{
isInvestigating = false;
return NodeState.Success;
}
2026-06-03 13:42:09 +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-04 15:41:01 +07:00
if (player == null) return NodeState.Failure;
2026-06-03 13:42:09 +07:00
2026-06-05 14:10:16 +07:00
agent.isStopped = true; // Đứng lại để bắn
2026-06-04 21:26:19 +07:00
2026-06-05 14:10:16 +07:00
// Xoay người 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 14:10:16 +07:00
// Bắ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
Debug.Log("Laser Shot!");
2026-06-03 13:42:09 +07:00
}
#endregion
2026-06-05 14:10:16 +07:00
#region DODGE MECHANIC
private IEnumerator DodgeRoutine()
{
Debug.Log("Dodging!");
isDodging = true;
nextDodgeTime = Time.time + dodgeCooldown;
// 1. Tắt AI tìm đường để Vật lý tiếp quản
agent.enabled = false;
rb.isKinematic = false; // Đảm bảo Rigidbody có thể nhận lực
// 2. Tính toán hướng né: Random nhảy sang Trái hoặc Phải
int randomDirection = Random.Range(0, 2) == 0 ? -1 : 1;
// Lấy vector hướng ngang của NPC nhân với trái (-1) hoặc phải (1)
Vector3 dodgeDir = transform.right * randomDirection;
// Có thể cộng thêm một chút lực nhảy lên (trục Y) nếu muốn NPC hơi nảy lên
// dodgeDir.y = 0.5f;
// 3. Tác dụng lực đẩy tức thời (Impulse)
rb.AddForce(dodgeDir * dodgeForce, ForceMode.Impulse);
// 4. Chờ NPC văng đi trong thời gian chỉ định
yield return new WaitForSeconds(dodgeDuration);
// 5. Thắng gấp (Dừng toàn bộ gia tốc vật lý lại)
// Lưu ý: Unity 6 dùng linearVelocity thay vì velocity như các bản cũ
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
// 6. Bật lại AI tìm đường
rb.isKinematic = true; // Trả lại Rigidbody về trạng thái không ảnh hưởng vật lý
agent.enabled = true;
isDodging = false;
}
#endregion
// Vẽ FOV trên Scene để dễ debug
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(transform.position, viewRadius);
Vector3 viewAngleA = DirFromAngle(-viewAngle / 2);
Vector3 viewAngleB = DirFromAngle(viewAngle / 2);
Gizmos.color = Color.yellow;
Gizmos.DrawLine(transform.position, transform.position + viewAngleA * viewRadius);
Gizmos.DrawLine(transform.position, transform.position + viewAngleB * viewRadius);
}
private Vector3 DirFromAngle(float angleInDegrees)
{
angleInDegrees += transform.eulerAngles.y;
return new Vector3(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad), 0, Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));
}
2026-05-30 17:41:31 +07:00
}