I am making an endless shooter and I just can’t figure out how to make the enemies stay away from other enemies. Here is my script that makes the enemy find the player, then attacks it:
public class EnemyAI : MonoBehaviour
public float AIspeed;
public Transform AItarget;
AItarget = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
int rand = Random.Range(2, 5);
AIspeed = rand;
transform.position = Vector3.MoveTowards(transform.position, AItarget.position, AIspeed * Time.deltaTime);
Ok, I found a solution (after 4 days of messing around in the engine, mind you):
- On the Enemy Gameobject (or any other GameObject that you don’t want colliding with others of its kind), make an Empty Gameobject and child it to the Enemy Gameobject.
- Add a Box Collider 2D component to the Empty Gameobject.
- Adjust the collider to what you want.
- Make a new layer for the Empty Gameobject.
- Go to Edit (at the top right of your screen) > Project Settings > Physics2D > Collision Matrix
- From here, make sure nothing collides with the Empty Gameobject layer except the Enemy Gameobject and itself.
- If you think the Enemy Gameobjects are staying a little too far away from each other, make the Empty Gameobject’s Box Collider2D smaller; vice versa.
Please note that this is probably a very bad and inefficient method of doing this but this is the only way I could think of