In my game I have multiple enemies. These enemies move towards the player.
However if the player circles around the enemies the enemies group up and eventually you only see one enemy. How can I keep this from happening?
Should look into group steering behaviors. What you are looking for in your question is a separating behavior. A simple way can be done by casting a sphere around each enemy to look for other enemies. Then have each enemy move away from the others. I put together something simple that you can put directly after the code you provided:
float separateSpeed = speed/2f;
float separateRadius = 1f;
Vector2 sum = Vector2.zero;
float count = 0f;
// overlapshere to detect others
var hits = Physics.OverlapSphere(transform.position, separateRadius);
foreach(var hit in hits) {
// make sure it is a fellow enemy ** use your enemy script name **
if(hit.GetComponent<Enemy>() != null && hit.transform != transform) {
// get the difference so you know which way to go
Vector2 difference = transform.position - hit.transform.position;
// weight by distance so being closer means moving more
difference = difference.normalized / Mathf.Abs(difference.magnitude);
// add together to get average of the group
// this allows those at the edges of a group to move out while
// the enemies in the center of a group to not move much
sum += difference;
count++;
}
}
if (count > 0) {
// average the direction
sum /= count;
// set the speed of movement
sum = sum.normalized * separateSpeed;
// this is where you would apply this vector for movement
// i am basing this off of the code you provided
transform.position = Vector2.MoveTowards(transform.position, transform.position + (Vector3)sum, separateSpeed * Time.deltaTime);
}