- Home /
Complex Enemy follow AI
I am trying to make a top down shooter with very basic enemies that only move towards the player at all times. When I implemented a very basic follow script it worked alright but the enemies would just eventually pile up on top of each other due to the fact that they are all handled by the same line. Is there a way to implement a curve or something of a random (but still efficient) nature that can be applied in order to make enemies seem relatively unique and more exciting.
You can make manual multiple paths that an enemy can follow and try to randomize it on the basis that the enemies are on left, center or right of the player.
Answer by mseever2022 · May 27, 2019 at 05:18 AM
I look around and I found this code that you can try and put in. Cause what your looking for in your question I believe is enemy separating, so they don't group up. Here is the code and I'll also link to the Unity Question and Answer I found it on cause it will probably give you more details.
float separateSpeed = speed/2f;
float separateRadius = 1f;
Vector2 sum = Vector2.zero;
float count = 0f;
// overlapshere to detect others
var hits = Physics.OverlapSphere(transform.position, separateRadius);
foreach(var hit in hits) {
// make sure it is a fellow enemy ** use your enemy script name **
if(hit.GetComponent<Enemy>() != null && hit.transform != transform) {
// get the difference so you know which way to go
Vector2 difference = transform.position - hit.transform.position;
// weight by distance so being closer means moving more
difference = difference.normalized / Mathf.Abs(difference.magnitude);
// add together to get average of the group
// this allows those at the edges of a group to move out while
// the enemies in the center of a group to not move much
sum += difference;
count++;
}
}
if (count > 0) {
// average the direction
sum /= count;
// set the speed of movement
sum = sum.normalized * separateSpeed;
// this is where you would apply this vector for movement
// i am basing this off of the code you provided
transform.position = Vector2.MoveTowards(transform.position, transform.position + (Vector3)sum, separateSpeed * Time.deltaTime);
}
and if its a 2D game change:
var hits = Physics.OverlapSphere(transform.position, separateRadius);
to:
var hits = Physics2D.OverlapCircleAll(transform.position, separateRadius);
(Link to original Q&A: https://answers.unity.com/questions/1608266/stop-enemies-from-grouping-up.html )
But with this script aren't you still grouping them together. They just wont overlap. I am trying to give the enemies a little more depth by making each approach unique
Your answer
Follow this Question
Related Questions
Raycasting AI 0 Answers
Enemy keeps moving in one direction. Help pls! 2 Answers
Enemy AI Not Working? 0 Answers
Looping Between Waypoints 1 Answer
How do I make a enemy follow me 3 Answers