41 lines
1.4 KiB
C#
41 lines
1.4 KiB
C#
using UnityEngine;
|
|
|
|
public class EnemyController : MonoBehaviour {
|
|
private GameObject player;
|
|
public float enemySpeed = 2f;
|
|
public float minDistance = 0.5f; // Minsta avstånd mellan fiender
|
|
|
|
void Start() {
|
|
player = GameObject.FindWithTag("Player");
|
|
}
|
|
|
|
void Update() {
|
|
if (player != null) {
|
|
// Beräkna riktning mot spelaren
|
|
Vector3 direction = (player.transform.position - transform.position).normalized;
|
|
|
|
// Kontrollera om det finns andra fiender nära
|
|
Collider2D[] nearbyEnemies = Physics2D.OverlapCircleAll(transform.position, minDistance);
|
|
foreach (Collider2D enemy in nearbyEnemies) {
|
|
if (enemy.gameObject != this.gameObject && enemy.CompareTag("Enemy")) {
|
|
// Flytta bort från den andra fienden
|
|
Vector3 away = (transform.position - enemy.transform.position).normalized;
|
|
direction += away; // Justera riktningen
|
|
}
|
|
}
|
|
|
|
// Normalisera riktningen igen
|
|
direction = direction.normalized;
|
|
|
|
// Flytta fienden mot spelaren (med justerad riktning)
|
|
transform.position += direction * enemySpeed * Time.deltaTime;
|
|
}
|
|
}
|
|
|
|
void OnDrawGizmosSelected() {
|
|
// Rita cirkeln i Scene för att se minDistance
|
|
Gizmos.color = Color.red;
|
|
Gizmos.DrawWireSphere(transform.position, minDistance);
|
|
}
|
|
}
|