I have been learning the basics of game development and made significant progress.
I would like to get some advice regarding Enemy movement. In particular I would like to know how to make sure multiple enemies on the screen follow a single target (Player) without glitching/bumping into each other.
A little bit about my configuration:
I have a simple PlayerFollower script attached to the Enemy prefabs:
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Callbacks;
using UnityEngine;
public class PlayerFollower : MonoBehaviour
{
//set the values in the inspector
private Transform target; //drag and stop player object in the inspector
public float within_range;
public float speed;
void FixedUpdate()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
//get the distance between the player and enemy (this object)
float dist = Vector3.Distance(target.position, transform.position);
//check if it is within the range you set
if (dist <= within_range)
{
//move to target(player)
if (dist > 2.0f)
{
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.fixedDeltaTime);
}
else{
//stop moving
transform.position = this.transform.position;
}
}
}
}
As you can see from above, its quite simple and self explanatory. The enemy is trying to reach the position of the Player. If the distance is < 2 then the enemy will stop moving.
Both the Enemy and Player have the same settings:
RB Body type: Dynamic
Mass: 1
Collision Detection : Continuous
Layer: Default
Sorting Layer: Default
Order in Layer 0
I would like to know how to ensure the enemies stop glitching on top of each other without adding significant complexity to the project. Does it have to do with the Dynamic body type and mass of the enemy or the player? Does it have to do with the layers the enemy/player are in? Does it have to do anything with the colliders?
Appreciate any tips in advance.
For a quick demonstration I have made a GIF: