Warcraft III resources & community, 2003–2006 · archived

GetNearestUnit

not rated
Submitted by YakAI0 downloads
This function returns the unit with the smallest distance from the location "loc". I is useful for AI's and spells like chainlightning.

Source

function GetNearestUnit takes location loc, boolexpr unitfilter, real radius returns unit
    local group g = GetUnitsInRangeOfLocMatching(radius, loc, unitfilter)
    local unit u1
    local unit u2
    local integer unitint
    local location UnitLoc1
    local location UnitLoc2

        loop
          exitwhen CountUnitsInGroup(g) <= 1

            set u1 = GroupPickRandomUnit(g)
            call GroupRemoveUnitSimple( u1, g )
            set UnitLoc1 = GetUnitLoc(u1)

            set u2 = GroupPickRandomUnit(g)
            call GroupRemoveUnitSimple( u2, g )
            set UnitLoc2 = GetUnitLoc(u2)

                if DistanceBetweenPoints(loc, UnitLoc1) < DistanceBetweenPoints(loc, UnitLoc2) then

                    call GroupAddUnitSimple( u1, g )

                else

                    call GroupAddUnitSimple( u2, g )

                endif

            call RemoveLocation(UnitLoc1)
            call RemoveLocation(UnitLoc2)

        endloop

    set u1 = GroupPickRandomUnit(g)

    call RemoveLocation(loc)
    call DestroyGroup(g)

    set UnitLoc1 = null
    set UnitLoc2 = null
    set unitint = H2I(u1)
    set g = null
    set u1 = null
    set u2 = null

    return unitint
    return null
endfunction

Comments

2
:roll: i am amazed that you know jass seeing that you skipped algorithms 101 in highschool...

here's how the things should look (pseudo-syntax):


set g = your init (from above)
if number of units in g == 0 return <no unit>
set closest_unit = get first unit from g
set min_distance = distance for unit closest_unit
call remove unit from group( closest_unit, g )
loop: for each unit in g   /*enumeration, not random*/
    set t_unit = picked unit
    set t_distance = distance for unit t_unit
    call remove unit from group( t_unit, g )
    if t_distance < min_distance then
        set min_distance = t_distance
        set closest_unit = t_unit
    endif
endloop
return closestunit
yeah! it's very useful! :D i have wanted to know how to do this for so long :roll:

but can't i get this as a trigger :? i don't do JASS :cry: