Advertisement
Aveneid

Find Closest Object

Jul 22nd, 2018
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. //Actor structure
  3. function Actor( posx, posy){
  4.     this.posx = posx;
  5.     this.posy = posy;
  6. }
  7.  
  8. //calc abs from a to b
  9. function dist(a,  b){return Math.abs(b-a);}
  10.  
  11.  
  12. //finds nearest entity and return it ID
  13. function findNearest(MainActor){
  14.     var nearest = 0;
  15.     if(ActorList[0].posx === MainActor.posx && ActorList[0].posy === MainActor.posy){
  16.         var minDistX = dist(MainActor.posx,ActorList[1].posx);
  17.         var minDistY = dist(MainActor.posy,ActorList[1].posy);
  18.         var minDist = dist(minDistX,minDistY);
  19.         } else {
  20.         var minDistX = dist(MainActor.posx,ActorList[0].posx);
  21.         var minDistY = dist(MainActor.posy,ActorList[0].posy);
  22.         var minDist = dist(minDistX,minDistY);
  23.     }
  24.     for(var i = 0; i < ActorList.length; i++){
  25.         if(ActorList[i].posx === MainActor.posx && ActorList[i].posy === MainActor.posy) continue;
  26.         else{
  27.            
  28.             minDistX = dist(MainActor.posx,ActorList[i].posx);
  29.             minDistY = dist(MainActor.posy,ActorList[i].posy);
  30.             if(dist(minDistX,minDistY)<minDist){
  31.                 minDist = dist(minDistX,minDistY);
  32.                 nearest = i;
  33.             }
  34.         }
  35.     }  
  36.     return nearest;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement