Prevent two enemies from going into each other

hey guys,
I am pretty new to Unity and tried to make a little game.
There I made a quick Skript for an Enemy that is chasing the player.
Thats the SKript I used:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyChaseSkript : MonoBehaviour
{
public GameObject target;
public float ChaseSpeed;

// Update is called once per frame
void Update()
{
    transform.position = Vector2.MoveTowards(transform.position, target.transform.position, ChaseSpeed *Time.deltaTime);
}

}

Now I want to have two of these Enemies.
I dupplicated them and both followed me.
But here is the problem. After a few Seconds they just go into each other.
I dont now how to stop them going into each other. I added a 2D Collider and 2D Rigidbodies but nothing helped and i couldnt find anything about it in the Internet.
I hope you can help me :slight_smile:

Add in object avoidance code. Probably the easiest way is to use 3 rays to detect enemies in your path and then you steer them away from each other using some vector math or rotation, So if an enemy triggers a ray, then you steer away from that ray…

Hey there,

to solve this you have to understand how you can move objects in different ways in unity. The method you chose is to directly set the position of the enemies. you take the current position, calculate the next frames position with the timedelta and chaseSpeed and you directly set the new position.

With this, the rigidbody will never check for collisions as it itself does not realize that it has been moved.

To make this work you have the choice to either:
Use the Rigidbodys MovePosition function or use forces on the rigidbody to move it. In your current case you probably want to take the first option. (See the manual for this function with a script example here)

You must do this in FixedUpdate and then the Rigidbodies will actually begin to work and check for collisions before they move into each other.

I’d suggest you play around with this for a bit and if you have further questions come back here then.

Thanks guys I will try out this things and write again if I have some questions: Is there a way to contact you privat in this forum?

So if you’re just changing the enemies’ position like this, there won’t be collision as you are saying. You could instead maybe use Rigidbody.AddForce()

If that doesn’t work, comment on this, because I have one more idea, but it’s kind of hard and won’t look as good. Hope it works! If it does, please click “Accept Answer”