Created
September 8, 2014 18:29
-
-
Save veeneck/a87b942a30a74a6bbef4 to your computer and use it in GitHub Desktop.
Find closest unit to a position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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