Advertisement
Guest User

Find Closest Object

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