# Best way to get the shortest Distance of many?

## Recommended Posts

I'm splitting Altis up into sectors by placing 14 markers down named Sector1 through Sector14. I'm using this in a script so I can find out which Sector a player is closest to and use that information to accomplish spawning an enemy patrol within the area of the player...

so I have this:

_unit = _this;

_apos = [];
_Sector1 = getMarkerPos "Sector1";
_Sector2 = getMarkerPos "Sector2";
_Sector3 = getMarkerPos "Sector3";
_Sector4 = getMarkerPos "Sector4";
_Sector5 = getMarkerPos "Sector5";
_Sector6 = getMarkerPos "Sector6";
_Sector7 = getMarkerPos "Sector7";
_Sector8 = getMarkerPos "Sector8";
_Sector9 = getMarkerPos "Sector9";
_Sector10 = getMarkerPos "Sector10";
_Sector11 = getMarkerPos "Sector11";
_Sector12 = getMarkerPos "Sector12";
_Sector13 = getMarkerPos "Sector13";
_Sector14 = getMarkerPos "Sector14";

I've only been able to test it so far between two sectors with this:

if (_unit distance _sector1 < _unit distance _sector2) then
{_apos = pos1}else{_apos = pos2};

It works fine BUT I need to now implement ALL the sectors to cover the whole map.

So how would I get the distance between the player and each sector, and THEN determine which one is the shortest distance?

##### Share on other sites

Copy the function below into your init.sqf to define the function, then call it like so:

SectorArray = ["sector1", "sector2", "sector3"];
NearestMarker = [sectorArray, player] call Zen_FindMinMarkerDistance;

The function itself:

Zen_FindMinMarkerDistance = {
/*
* Evaluates the distance between each element of an array and a given center
* Params    1. Array of markers, the array evaluate
*           2. Object, position, or marker, the center
* Return:   Element of array that is closest to the center
*/
private ["_testArray","_center","_outElement"];

_testArray = _this select 0;
_center =  _this select 1;

if (typeName _center == "STRING") then {
_center = getMarkerPos _center;
};
_outElement = _testArray select 0;

{
if (((getMarkerPos _x) distance _center) < (_center distance (getMarkerPos _outElement))) then {_outElement = _x;};
} forEach _testArray;

_outElement
};

This function only accepts an array of markers, it can be changed to accepts objects and positions, but that requires more code that you do not seem to need. It does accept an object, position, or marker for the center. This function will return the name of the marker, not its position.

##### Share on other sites

Awesome! Thank you!