Skip to content

Instantly share code, notes, and snippets.

@veeneck
Created September 8, 2014 18:29
Show Gist options
  • Select an option

  • Save veeneck/a87b942a30a74a6bbef4 to your computer and use it in GitHub Desktop.

Select an option

Save veeneck/a87b942a30a74a6bbef4 to your computer and use it in GitHub Desktop.
Find closest unit to a position
func findClosestUnitToPosition(destination:CGPoint, var positionedUnits:Array<CharacterNode>) -> CharacterNode {
var closestUnit : CharacterNode? = nil
var closestDistance : CGFloat? = nil
// Loop over all of our units.
for(i, unit) in enumerate(self.units) {
// If the unit hasn't been moved already.
if(!contains(positionedUnits, unit)) {
// Helper function to calculate distance using hypotf()
let distance = Coordinates.calculateDistance(unit.position, end: destination)
// If no unit has been marked closest yet, set our first to closest.
if(closestUnit == nil) {
closestUnit = unit
closestDistance = distance
}
// Else, if this unit is actually closer than the closest, set it as the new closest.
else {
if(distance < closestDistance) {
closestDistance = distance
closestUnit = unit
}
}
}
}
return closestUnit!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment