Game Development Community

Closest node from AIPlayer

by Jeff Brown · in Torque Game Engine · 02/05/2009 (5:50 pm) · 4 replies

I found some code for simple AI (chase, unchase) and when he enters the UNCHASE state, he follows his breadcrumbs back to the path. I want him to go straight to the closest node when he enters the UNCHASE state.

for(%i = 0; %i < path1.getCount(); %i++)
{
  %nodePos = path1.getObject(%i).getTransform();
  %botPos = %this.getTransform(); //%this refers to the AIPlayer
  %dist = VectorDist(%nodePos, %botPos);
  %node = path1.getObject(%i);
  error("Node # " @ %node);       // name of each node
  error("Node Pos = " @ %nodePos);// position of each node
  error("Distance: " @ %dist);    // distance of each node from AIPlayer
//  if(%dist < %previousDist)
//  { 
//     %dist = %shortestDist;
//  } 
}
//error("Shortest dist " @ %shortestDist);
With this code I can get the distances of the nodes from the AIPlayer, but I don't know how to get the position of the node that has the shortest distance from the AIPlayer. (The commented out code was a previous attempt)

#1
02/05/2009 (9:29 pm)
Here's the code I used in the Improved AI Guard Unit resource to do the same thing that you're trying to do.

%dist = 0;
   %tempdist = 0;
   %index = -1;
   %botpos = %this.getposition();
   %count = %path.getCount();
   //Cycle through all nodes on this path and set the closest node as the bot's current location
   while ((%node = %count) != 0)
   {
     	%nodepos = %this.path.getObject(%count - 1).getposition();
		%tempdist = vectorDist(%nodepos, %botpos);

		if(%tempdist < %dist || %dist == 0)
		{
			%dist = %tempdist;
			%index = %node;
		}
     	%count--;
   }
   %index = %index - 1;
   %this.moveToNode(%index);

   if (%index > %path.getCount() - 1)
   {
      %this.targetNode = %path.getCount() - 1;
   }
   else
   {
      %this.targetNode = %index;
   }

That resource has a lot of good example code that you might want to check out, and most of it is commented better than this section is.
#2
02/05/2009 (10:23 pm)
Forgive the density, but this loop that you're doing:

while ((%node = %count) != 0)

I've never seen that type of control structure.....is it shorthand for another, more traditional way of doing a loop?



#3
02/05/2009 (10:29 pm)
I believe that line of code is equivalent to:

while (%count != 0)
{
%node = %count;

But I'm not really sure what I was thinking when I wrote that.

// I need to comment more.
#4
02/05/2009 (10:45 pm)
OK thanks, that makes more sense.... but the original code...that intrigues me. Let me know if you can remember why you did it like that.