Snippet GetNearestUnitInRangeOfUnit

substance

New Member
Reaction score
34
This function uses Group Recycling and an 'always true' boolexp (ALL) although you can feel free to edit it.
JASS:
function GetNearestUnitInRangeOfUnit takes unit nearestUnit, real radius returns unit
    local real x = GetUnitX(nearestUnit)
    local real y = GetUnitY(nearestUnit)
    local real x2
    local real y2
    local real currentDistance
    local real nearestDistance = radius
    local unit currentUnit
    local group unitGroup = NewGroup()
    
    call GroupEnumUnitsInRange(unitGroup,x,y,radius,ALL)
    call GroupRemoveUnit(unitGroup,nearestUnit)
    
    loop
       set currentUnit = FirstOfGroup (unitGroup)
       exitwhen currentUnit == null
       set x2 = GetUnitX(currentUnit) - x
       set y2 = GetUnitY(currentUnit) - y 
       set currentDistance = SquareRoot(x2*x2 + y2*y2)
       if currentDistance < nearestDistance then
          set nearestUnit = currentUnit      
          set nearestDistance = currentDistance          
       endif
       call GroupRemoveUnit(unitGroup,currentUnit)
    endloop
    
    call ReleaseGroup(unitGroup)
    return nearestUnit
endfunction


Example

JASS:
function KillClosestUnitFromCaster takes nothing returns nothing
call KillUnit(GetNearestUnitInRangeOfUnit(GetTriggerUnit(),500))
endfunction
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top