If your factory has constructed a vehicle, you want the vehicle to get away from the entrance of the factory. If a siberite bomb explodes in the middle of your base, people have to get out of there fast. And you certainly wanna keep your scientists, engineers and mechanics in safe distance of enemy soldiers/vehicles. All these things can be done with a simple ComMoveXY command, but it is often difficult to predict, where the units should go to get away as fast as possible. This function is the solution (I apologize if I sound like I have invented a remedy for all illnesses

).

Simply write which unit should get away from what hex and how far he/she/it should get away. The function then makes the unit pick the shortest way avoiding walking into environmental objects, other units or out of the map.

**Code:**

Export Function GetAwayFromXY(unit1, x, y, dist);

var list_coords, a, min_dist, b, c, list_nearest, d, rand_num, rand_near_hex, e;

begin

if not IsOk(unit1) or dist = 1 or not ValidHex(x, y) then Exit;

list_nearest = [];

list_coords = [[x,y-dist],[x+dist,y],[x+dist,y+dist],[x,y+dist],[x-dist,y],[x-dist,y-dist]];

a = 1;

while a <= dist - 1 do

begin

list_coords = Insert(list_coords, 1, [x+a,y-dist+a]);

list_coords = Insert(list_coords, 1, [x+dist, y+a]);

list_coords = Insert(list_coords, 1, [x+dist-a, y+dist]);

list_coords = Insert(list_coords, 1, [x-a, y+dist-a]);

list_coords = Insert(list_coords, 1, [x-dist, y-a]);

list_coords = Insert(list_coords, 1, [x-dist+a, y-dist]);

a = a + 1

end;

repeat

if list_coords = 0 then exit;

min_dist = 5000;

for b in list_coords do

if GetDistUnitXY(unit1, b[1], b[2]) < min_dist then min_dist = GetDistUnitXY(unit1, b[1], b[2]);

c = 0;

repeat

c = c + 1;

if GetDistUnitXY(unit1, list_coords[c][1], list_coords[c][2]) = min_dist then

begin

list_nearest = Insert(list_nearest, 1, [list_coords[c][1], list_coords[c][2]]);

list_coords = Delete(list_coords, c);

c = c - 1;

end;

until c = list_coords;

Randomize;

d = 0;

repeat

rand_num = Rand(1,list_nearest);

rand_near_hex = list_nearest[rand_num];

if ValidHex(rand_near_hex[1], rand_near_hex[2]) and HexInfo(rand_near_hex[1], rand_near_hex[2]) = 0 then

begin

d = 1;

end

else list_nearest = Delete(list_nearest, rand_num);

until d = 1 or list_nearest = 0 or not IsOK(unit1);

until d = 1 or not IsOK(unit1);

ComMoveXY(unit1, rand_near_hex[1], rand_near_hex[2]);

end;

EDIT1: Fixed the initial part so the correct hexes will be put in list_coords