AI Truy đuổi Người chơi (Chase)
C# Code
using UnityEngine;
public class AIChase : MonoBehaviour
{
public Transform playerTransform;
public float moveSpeed = 4f;
public float detectionRange = 10f;
public float stopChasingRange = 15f;
private bool isChasing = false;
void Update()
{
if (playerTransform == null)
{
// Cố gắng tìm người chơi nếu chưa có tham chiếu
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player != null) playerTransform = player.transform;
else return; // Không tìm thấy người chơi
}
float distanceToPlayer = Vector3.Distance(transform.position, playerTransform.position);
if (isChasing)
{
// Nếu đang đuổi, tiếp tục di chuyển tới người chơi
transform.position = Vector3.MoveTowards(transform.position, playerTransform.position, moveSpeed * Time.deltaTime);
// Nhìn về phía người chơi
transform.LookAt(playerTransform);
// Nếu người chơi ra khỏi phạm vi dừng, ngừng đuổi
if (distanceToPlayer > stopChasingRange)
{
isChasing = false;
}
}
else
{
// Nếu người chơi vào trong phạm vi phát hiện, bắt đầu đuổi
if (distanceToPlayer < detectionRange)
{
isChasing = true;
}
}
}
// Vẽ phạm vi trong Editor
void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, detectionRange);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, stopChasingRange);
}
}AI sẽ phát hiện người chơi trong một phạm vi nhất định và bắt đầu di chuyển về phía họ. Khi người chơi ra khỏi phạm vi, AI sẽ dừng lại.