The Hunting Function
The purpose of this function is to locate the nearest target, and assign that target to the NPC.
My example here is written to hunt compus.  So if you put this guy in a level with you, he will hunt the baddys alongside you.
Later you will notice that this is the only function that even mentions the compus, even though that is what the baddy hunts.
Note: just change all the "compu" to "player" and this baddy will hunt players, with a timereverywhere in the Initialize function, the baddy will be on-line ready.
Hell, you could script a bomb defuser by changing all the compu's to bomb's.
Or a sick weirdo with a horse fetish...
 
function Hunt(){ 
  this.curdist=64; 
  for (i=0;i <compuscount;i ++){ 
    if (!compus[ i].mode==5||!compus[ i].mode==9){ 
      this.distx=abs(compu s[i].x-x); 
      this.disty=abs(compu s[i].y-y); 
      this.dist=((this.distx*this.distx)+(this.disty*this.disty))^.5; 
      if (this.dist <this.curdist){ 
        this.curdist =this.dist
        this.index =i
      } 
    } 
  } 
  this.testx=compu s[this.index].x; 
  this.testy=compu s[this.index].y; 
}
First of all, this sets the variable this.curdist equal to 64.  This is just to basically reset the distance to the baddys target to prevent weird glitches that may happen later.  Then it starts a for loop that will be used to keep track of the vital stats of all the compus on the level.  First thing within that loop is it checks to make sure that the compu of index i is not in the process of dying, or already dead.  If not, then it gets the distance from the NPC to compu[i] and stores it at this.dist. (There is an entire section on a "Distance" function later, so I won't go into to much detail here.)  Then this function checks to see if the distance it just got, this.dist, is less than the previous distance it checked, denoted this.curdist .  If it is, then that means the baddy just checked is closer to the NPC than the previously checked baddy; as a result, this.curdist is set equal to this.dist, and this.index is set equal to i, which of course is the index of the baddy we just got the distance to! When the for loop has finally finished executing, then this.testx and this.testy are set to the x and y values of the compu with an index of this.index , which we found to be the closest baddy to the NPC through the previous process.
This will be called frequently during a baddy's lifetime.  It has to be called before the baddy moves toward its target, before it attacks, and during some optional stuff, like if you want it to face its target, then it needs to actually know what its target is, and so on.
 
Previous Topic         Home           Next Topic