Finding the point at the center of a group of units

Status
Not open for further replies.
Level 6
Joined
Nov 3, 2005
Messages
103
I'm trying to find the x and y coordinates of the center of a group of units. Assumably it would normally be done by calculating each and every X value of each unit in the group, and then dividing (averaging) the value with the amount of units within the group. Seems like it would be somewhat of a simple task in written code, but doing it using triggers is a nightmare. Anyone know how you would go about this?
 
Level 12
Joined
Feb 22, 2010
Messages
1,115
Your approach is correct, it can be done like this.

  • Set X = 0.00 (real variable)
  • Set Y = 0.00 (real variable)
  • Set Count = 0 (integer variable)
  • Unit Group - pick every units in yourgroupvariable and do
    • Set X = X + x coordinate of picked unit
    • Set Y = Y + y coordinate of picked unit
    • Set Count = Count + 1
  • Set X = X / Count
  • Set Y = Y / Count
 
Level 6
Joined
Nov 3, 2005
Messages
103
I've tried this and even switched some of the variables around and I keep getting the same result. If there's more than one unit within the group the game averages the coordinates of the first unit I added into the group via init and the center of the map. When there's only one unit in the group then the game sets the value to the position of that single unit.
 
Post your trigger attempt. Your method should work.

Or try this snippet. It might contain errors, and it might not work at all:
JASS:
function GetGroupCenterPoint takes group g returns location
    local integer index = 0
    local unit array u
    local unit fog
    local real x = 0
    local real y = 0
    loop
        set fog = FirstOfGroup(g)
        exitwhen fog == null
        call GroupRemoveUnit(g, fog)
        set u[index] = fog
        set x = x + GetUnitX(fog)
        set y = y + GetUnitY(fog)
        set index = index + 1
    endloop
    if index == 0 then
        return Location(0, 0)
    endif
    set x = x / index
    set y = y / index
    loop
        exitwhen index == 0
        set index = index - 1
        call GroupAddUnit(g, u[index])
        set u[index] = null
    endloop
    return Location(x, y)
endfunction

Just copy the code, paste it into your map's header (if you don't know where to find this, click me), and then use it like so:
  • ----- Assume you have a group variable "TempGroup" -----
  • ----- Assume you have a point variable "TempPoint" -----
  • Custom script: set udg_TempPoint = GetGroupCenterPoint(udg_TempGroup)
  • ----- Use "TempPoint" in your code for whatever you need -----
 
Status
Not open for further replies.
Top