UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"flow field movement for enemies looking for the nearest target"
// This is an example of flow field movement for enemies in Unity, using a 2D grid of vectors to determine direction public class EnemyMovement : MonoBehaviour { public float moveSpeed = 5f; public float turnSpeed = 5f; public float detectionRadius = 10f; private Vector2[,] flowField; private Transform target; void Start() { // Generate a flow field flowField = GenerateFlowField(); // Find the nearest target target = FindNearestTarget(); } void Update() { // Get the current position of the enemy Vector2 position = new Vector2(transform.position.x, transform.position.z); // Get the vector from the flow field at the current position Vector2 flowVector = GetFlowVector(position); // Rotate the enemy towards the flow vector Quaternion targetRotation = Quaternion.LookRotation(new Vector3(flowVector.x, 0f, flowVector.y)); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime); // Move the enemy in the direction of the flow vector Vector3 movement = new Vector3(flowVector.x, 0f, flowVector.y) * moveSpeed * Time.deltaTime; transform.position += movement; } Vector2[,] GenerateFlowField() { // Create a 2D grid of vectors Vector2[,] flowField = new Vector2[10, 10]; // Calculate a flow vector for each cell in the grid for (int x = 0; x < flowField.GetLength(0); x++) { for (int y = 0; y < flowField.GetLength(1); y++) { Vector2 cellPosition = new Vector2(x, y); Vector2 cellFlowVector = CalculateFlowVector(cellPosition); flowField[x, y] = cellFlowVector; } } return flowField; } Vector2 CalculateFlowVector(Vector2 position) { // Calculate a flow vector based on the distance to the nearest target Transform nearestTarget = FindNearestTarget(position); Vector2 targetPosition = new Vector2(nearestTarget.position.x, nearestTarget.position.z); Vector2 direction = (targetPosition - position).normalized; return direction; } Transform FindNearestTarget(Vector2 position) { // Find the nearest target within a certain radius Collider[] colliders = Physics.OverlapSphere(transform.position, detectionRadius); Transform nearestTarget = null; float nearestDistance = Mathf.Infinity; foreach (Collider collider in colliders) { if (collider.CompareTag("Target")) { float distance = Vector3.Distance(position, collider.transform.position); if (distance < nearestDistance) { nearestTarget = collider.transform; nearestDistance = distance; } } } return nearestTarget; } Transform FindNearestTarget() { // Find the nearest target to the current position of the enemy return FindNearestTarget(new Vector2(transform.position.x, transform.position.z)); } Vector2 GetFlowVector(Vector2 position) { // Get the flow vector from the flow field at the given position int x = Mathf.RoundToInt(position.x); int y = Mathf.RoundToInt(position.y); return flowField[x, y]; } }