- Home /
How do I make enemies stay away from other enemies?
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:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour
{
public float AIspeed;
public Transform AItarget;
void Start()
{
AItarget = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
int rand = Random.Range(2, 5);
AIspeed = rand;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, AItarget.position, AIspeed * Time.deltaTime);
}
}
Thanks!
Answer by Zokaper · Nov 20, 2019 at 04:32 PM
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.
Done!
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 :/
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Distribute terrain in zones 3 Answers
Radial movement range for turn based strategy game 0 Answers
Multiple Cars not working 1 Answer