UnityScripterAI
Discord ↗
Link Copied to Clipboard
×
"create enemy movement script without overlapping and looking for the nearest target"
using UnityEngine; public class EnemyMovement : MonoBehaviour { public float moveSpeed = 3; private Transform target; void Start() { target = FindNearestTarget(); } void Update() { if (target != null) { transform.LookAt(target.position); transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed); if (Vector3.Distance(transform.position, target.position) < 1f) { target = FindNearestTarget(); } } } Transform FindNearestTarget() { GameObject[] targets = GameObject.FindGameObjectsWithTag("Player"); Transform nearestTarget = null; float closestDistance = Mathf.Infinity; foreach (GameObject target in targets) { float distance = Vector3.Distance(transform.position, target.transform.position); if (distance < closestDistance && !target.GetComponent<Collider>().bounds.Intersects(GetComponent<Collider>().bounds)) { closestDistance = distance; nearestTarget = target.transform; } } return nearestTarget; } }