Find survivor closest to entity - survivorclosest.nut

You can do something similar entity side, but someone asked me how to do it via script, so here you go.

This script includes findsurvivors.nut, so be sure to grab that too.

Here's how you would use it.... (or one way to, you can use triggers as well and all that


IncludeScript("survivorclosest.nut", this);

ent <- Entities.FindByName(null, "entname");

printl("Found entity "+ent);

FindSurvivors() // make sure this script isn't called right away or they won't be found yet

who <- FindSurvivorClosestToEnt(ent); // returns entity reference to survivor if (who){ printl(who); printl(who+" is closest to "+ent.GetName()+" at "+who.GetOrigin()); // do something here }else{ printl("Nothing found"); }

/* or, if you want the name returned (the key into the survivors table), add a true value as a second param */

who <- FindSurvivorClosestToEnt(ent, 1); // returns entity reference to survivor if (who){ printl(who); printl(who+" is closest to "+ent.GetName()+" at "+survivors[who].GetOrigin()); // do something here }else{ printl("Nothing found"); }



/*
survivorclosest.nut
author: Lee Pumphret
https://www.leeland.info

Call it with an entity reference and it will return the closest living survivor

!!!You need to have findsurvivors.nut as well as it's used by include.
@ https://www.leeland.info/findsurvivors-nut.html
*/

Msg("==========loading survivorclosest.nut==========\n")

IncludeScript("findsurvivors.nut", this);

function FindSurvivorClosestToEnt(ent, byindex=0){
   if (!survivors_found){
      printl("ERROR: You haven't called FindSurvivors() yet!, bailing")
      return;

   }


   if (ent && ent.IsValid()){
      porigin <- ent.GetOrigin();
      sdistance <- {};

      closest <- null;

      foreach(s,m in survivors){
         if (m.IsValid() && (m.GetHealth() > 1)){  // don't count players with 1 health, ie dead
            sorigin <- m.GetOrigin();
            sdistance[s] <- sqrt(pow(porigin.x - sorigin.x,2) + pow(porigin.y - sorigin.y,2)+pow(porigin.z - sorigin.z,2))
            printl(s+": distance is "+ sdistance[s] );
            if (!closest || sdistance[s] < sdistance[closest]){
               closest = s;
            }
         }
      }

      printl(closest+" is closest to "+ent);
      return byindex ? closest : survivors[closest]


   }else {
      printl("No Ent found!");

   }

}
Scroll to top