So I’m trying to come up with a relatively simple way for enemies to avoid each other within a radius while continuing to pursue the player, and I’m running into an issue where they WILL avoid each other with the method im using, but the issue is that they snap immediately into a position away from the other enemy.
The goal here is to, when the enemy is NOT close enough to attack, and the enemy’s distance to the other enemy is within “distanceToOther”, to rotate circularly over time towards the direction of the player. It’s moving in the correct direction, just not over a period of time smoothly, just snapping directly to it.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Transform player;
[Range(0, 3f)]
public float moveSpeed = 2f;
[Range(0, 20)]
public float damage;
[Range(0, 20)]
public float attackRadius;
private List<GameObject> otherEnemies = new List<GameObject>();
[Range(0f, 3f)]
public float distanceToOther;
Vector3 otherDirection;
private float pivotAngle;
private Rigidbody2D rb;
Vector3 direction;
[Range(0, 5)]
public float RotateSpeed = 2f;
[Range(0, 5)]
public float Radius = 1f;
private Vector3 pivot;
private float rotateAngle;
Vector3 offset;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
if (GameObject.FindGameObjectsWithTag("Enemy") != null)
{
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
if (enemy != this.gameObject)
{
otherEnemies.Add(enemy);
}
}
}
if (GameObject.FindWithTag("Player") != null)
{
player = GameObject.FindWithTag("Player").transform;
}
}
public void Update()
{
rotateAngle += RotateSpeed * Time.deltaTime;
offset = new Vector3(Mathf.Sin(rotateAngle), Mathf.Cos(rotateAngle)) * distanceToOther;
if (player)
{
FindPlayerLocation();
}
if (otherEnemies.Count > 0)
{
FindOtherEnemyLocations();
}
}
private void FindPlayerLocation()
{
direction = player.position - transform.position;
}
private void FindOtherEnemyLocations()
{
foreach (GameObject other in otherEnemies)
{
if (other)
{
otherDirection = gameObject.transform.position - other.transform.position;
}
}
}
public void FixedUpdate()
{
if (player)
{
if (Vector3.Distance(player.position, transform.position) > attackRadius)
{
rb.MovePosition(transform.position + direction.normalized * moveSpeed * Time.fixedDeltaTime * 100);
if (otherEnemies.Count > 0)
{
foreach (GameObject other in otherEnemies)
{
if (other)
{
if (Vector3.Distance(transform.position, other.transform.position) <= distanceToOther)
{
pivot = other.transform.position;
transform.position = pivot + offset;
}
}
}
}
}
else
{
//check if still cooling down
if (attackCooldown > 0)
{
//decrement if still cooling down
attackCooldown--;
}
//check attack cooldown
if (attackCooldown == 0)
{
AttackPlayer();
//reset the attack cooldown
attackCooldown = baseAttackCooldown;
}
}
}
}