AI Tuần tra (Patrol)
C# Code
using UnityEngine;
using System.Collections;
public class AIPatrol : MonoBehaviour
{
public Transform[] waypoints;
public float moveSpeed = 3f;
private int currentWaypointIndex = 0;
void Update()
{
if (waypoints.Length == 0) return;
// Di chuyển tới waypoint hiện tại
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypointIndex].position, moveSpeed * Time.deltaTime);
// Kiểm tra nếu đã đến gần waypoint
if (Vector3.Distance(transform.position, waypoints[currentWaypointIndex].position) < 0.1f)
{
// Chuyển sang waypoint tiếp theo
currentWaypointIndex = (currentWaypointIndex + 1) % waypoints.Length;
}
}
// Vẽ các đường nối waypoints trong Editor để dễ hình dung
void OnDrawGizmos()
{
if (waypoints == null || waypoints.Length < 2) return;
for (int i = 0; i < waypoints.Length; i++)
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(waypoints[i].position, 0.3f);
if (i > 0)
{
Gizmos.DrawLine(waypoints[i-1].position, waypoints[i].position);
}
}
Gizmos.DrawLine(waypoints[waypoints.Length-1].position, waypoints[0].position);
}
}Một script đơn giản cho AI để di chuyển tuần tự qua một danh sách các điểm (waypoints). Khi đến điểm cuối cùng, nó sẽ quay trở lại điểm đầu tiên.