- Home /
Unity3D : Enemies following the player keep moving through each other
Hi, I'm trying to make enemies follow the player, but also for them to collide with each other and other objects in my game. The "following" part works (I found some help for that here already), but as soon as I have multiple enemies, doesn't matter where they're placed, after some time chasing me they kind of all form into one, they overlap each other. This is the code for following the player : [CODE]using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class follow : MonoBehaviour {
public Transform Player;
public float MoveSpeed = 6f;
float MaxDist = 30f;
float MinDist = 5f;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
}
}
}[/CODE]
I'd really appreciate some help, I've been at this for quite some time.
Answer by BastianUrbach · Jan 11, 2018 at 12:01 PM
If you want enemies to be affected by Physics, you have to work with Unity's Rigidbody Component instead of modifying their position directly. If you set the position directly, the Rigidbody doesn't know your "intention", you might just want the object to "teleport" to its new position, rather than moving it smoothly and with respect to physics. To use Rigidbodies and allow collisions, try the following:
Attach a Collider component (e.g. "Sphere Collider") to your player and to the enemies if you haven't done so yet.
Attach a Rigidbody component to the enemies
Change
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
toGetComponent<Rigidbody>().velocity = transform.forward * MoveSpeed;
Thank you, it's a little bit better than before(the player and the enemies both had rigidbodies already, but I didn't know how to use it in the script, so thank you for that!), but it still doesn't work as it should - the enemies keep going through each other.
Here's a screenshot of two zombies (enemies) overlapping still :