• Hello [name]! Thanks for joining the GMC. Before making any posts in the Tech Support forum, can we suggest you read the forum rules? These are simple guidelines that we ask you to follow so that you can get the best help possible for your issue.

Need to know how to create Unit Formations in Game Maker Studio 1.4 - Need Help!

I am trying to create a multiplayer RTS game. I have already figured out how to have multiple players move units and have said units avoid other objects, like solid obstacles, yet now I would like to have the units arrange themselves in a formation or grid, once they reach their destination.

I use the variables "tx", and "ty" for the destination, yet I'd like to know how I can have the units automatically arrange themselves, possibly a simple AI of sorts, once they reach a set distance from the target x,y coordinates. If this can be solved with a simple script or AI, I would greatly appreciate it. If anyone can help me, it would be of a great help.
 

FrostyCat

Member
This is easy if you set each unit's destination separately.
  • Calculate the average x and y position of all selected units (i.e. the centroid).
  • For each selected unit:
    • Calculate the position difference between the unit and the centroid.
    • Go towards the target position plus the position difference from the previous step.
 
This is easy if you set each unit's destination separately.
  • Calculate the average x and y position of all selected units (i.e. the centroid).
  • For each selected unit:
    • Calculate the position difference between the unit and the centroid.
    • Go towards the target position plus the position difference from the previous step.
How would I be able to accomplish the above in code? Do I need to make a grid of some sort, or square root the total number of units to create said grid? If anyone can help me with that, I would greatly appreciate it.
 

FrostyCat

Member
Assuming that you have the selected units in a list, and the target is the mouse position:
GML:
// Calculating the centroid
var cx = 0;
var cy = 0;
var nSelectedUnits = ds_list_size(selectedUnits);
for (var i = nSelectedUnits-1; i >= 0; --i) {
    with (selectedUnits[| i]) {
        cx += x;
        cy += y;
    }
}
cx /= nSelectedUnits;
cy /= nSelectedUnits;

// For each selected unit
for (var i = nSelectedUnits-1; i >= 0; --i) {
    // Move to the target position plus the offset from the centroid
    // I am assuming that you already have code in the unit for moving towards (tx, ty)
    with (selectedUnits[| i]) {
        tx = mouse_x+x-cx;
        ty = mouse_y+y-cy;
    }
}
I strongly suggest that you brush up on basic loops and algorithms if you can't independently write the code based on the algorithm I provided. This is on the easy side among algorithms needed for a multiplayer RTS game. If you don't get up to speed, you'll just need to be bailed out over and over again.
 
Top