Multiple Units moving to Object.

HI Guys
Got a question. A bit of a easy one I think But I am just complicating things. I have units moving to a Big Enemy. They attack while moving. So this is not the issue. My issue is the movement. Thye all should move to the enemy Keep a distance between each other and the closest to the main enemy they are allowed is example 1f.

When I remove one of the front units the rest units should shift up to fill the gaps. Units move from the bottom upwards.

Any Help would be great!


My Script which is a total mess. Everything keeps pushing everything.

using UnityEngine;

public class CrowdMovement : MonoBehaviour
{
    [SerializeField]
    public Transform mainObject; // Reference to the main object
    public float movementSpeed = 2.0f; // Speed of movement
    public float spacing = 1.0f; // Desired spacing between objects


    private void Start()
    {

        mainObject = GameObject.FindGameObjectWithTag("Boss").transform;
    }
    void Update()
    {
        Vector2 direction = mainObject.position - transform.position;
        float distance = direction.magnitude;

        if (distance > spacing)
        {
            direction.Normalize();
            transform.position += (Vector3)direction * movementSpeed * Time.deltaTime;
        }
        else if (distance < spacing)
        {
            direction.Normalize();
            transform.position -= (Vector3)direction * movementSpeed * Time.deltaTime;
        }

        // Check for nearby objects and adjust position
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, spacing);
        foreach (Collider2D collider in colliders)
        {
            if (collider.gameObject != gameObject)
            {
                Vector2 pushDirection = (collider.transform.position - transform.position).normalized;
                transform.position -= (Vector3)pushDirection * movementSpeed * Time.deltaTime;
            }
        }
    }
}

Also . They never seem to stop moving. They Jitter!

If you need coordinated movement your choices are largely:

  • have each attacker try to figure out how far to stay from everybody

  • have an attacker manager that observes enemies and orchestrates their positioning

Instead of pathing directly TO the target, you can also have them path to a set of offset points, and make a manager (perhaps even on the target) that hands these points out to prospective attackers.

It gets hairier if you want to make sure everybody has a clear view of the target for ranged attacks… this is why it is helpful to have the target manage the points: it would only hand out points that are not obscured by other attackers or by terrain.

1 Like

No Need for clear view. The attacks are cosmetics/visual. It will be calculated in the background.
- have an attacker manager that observes enemies and orchestrates their positioning
What is in my head as well before I posted.
Where to start. That is my problem

The go-to example for any sort of agent-based crowd simulations is a famous algorithm called “boids”. If you research that term I’m sure you’ll find methods used for separation.

Edit: One solution for this would be raycast steering. I made a video about that, although it’s really meant more as a demonstration rather than a tutorial, so it doesn’t go in to as much detail as a tutorial would. I don’t how performant this will be with the number of units you have either.

Step 1: instead of saying “attacker, go to target!” change it to consult the formation manager.

“hey formation manager, I want to attack this target, where do I go?”

At first just have your manager return the target position! That will result in no change in how things work from right now… but you have created a layer between the attackers and the manager.

Step 2: make up a list of hard-coded offsets from the target and start handing them out in round-robin fashion to each subsequent caller.

If your target can go into weird locations then you might need to do more checking in step #2 before giving out invalid positions.

These two steps might be all you need.

Beyond that you could have the manager be generic (every attacker asks it how to attack) and if the target is a small enemy, it just gives out the target position. But if it is a larger enemy then perhaps it asks the target , “what are your list of points in front of you please?”

This also lets you change the formation manager to say “Sorry, this target has no more space to be attacked right now, try again later please!”

Generally these things are best approached step at a time, a little change, a little tweak, step by step closer, until you think “Hey man this is kinda fun now!”

You could use a point effector so that your units push away from one another while being pulled towards the boss.

1 Like

A good callout… but notice OP’s code: it isn’t actually using a Rigidbody2D, just doing a Physics2D overlap for collision, that’s it.

Otherwise it is transforms… transforms all the way down. :slight_smile:

The way I’ve handled this in the past is to simply use a supporting object that represents a formation and then make the agents move to a valid and available position in that formation. Each position within the formation can be defined at edit-time which saves you a lot of runtime work plus you can dynamically switch formation objects and then have agents re-assign themselves to a valid spot when that happens. Then the formation can be moved which will tow the agents along. You can also program the formation to support flagging positions as valid/invalid so that for example if a position would be inside of a wall or invalid play area the agents no longer try to assume that spot within the formation.

This isn’t exactly what you were looking for but it’s something along the line of what I described and might give you some ideas. GitHub - Slugronaut/GeniusFormations: A simple formation Leader/Follower system for Unity's NavMeshAgents

1 Like

Thanks everyone for the feedback. Appreciate it!