Game Development Community

dev|Pro Game Development Curriculum

Easy way to find the closest object!

by Aaron Fehlen · 11/21/2013 (1:28 pm) · 3 comments

Here's a quick snippet of code used to find the closest object to another object. It simply uses the distance formula d = sqrt((x1 - x2)^2 + (y1 - y2)^2).

I'm using it to find the nearest enemy to my base and set it as the audio listener. So the closer the bad guy gets to the base, the louder the music gets! Hope it helps!

function findClosestEnemy(%object)
{
	%list = myScene.getSceneObjectList();
	%count = %list.count;
	%closestDistance = 1000;
	%closestObj = 0;

    for( %i = 0; %i < %count; %i++ )
    {
         %obj = myScene.getObject( %i );
		 
         if( %obj.SuperClass $= "enemySuperClass" ) // filter out just the classes you want
         {
            %x1 = %obj.getPosition().x;
			%x2 = %object.getPosition().x;
			%y1 = %obj.getPosition().y;
			%y2 = %object.getPosition().y;
			
			// d = sqrt((%x1 - %x2)^2 + (%y1 - %y2)^2)
			%x = (%x1 - %x2) * (%x1 - %x2);
			%y = (%y1 - %y2) * (%y1 - %y2);
			%d = msqrt(%x + %y);
			
			if(%d < %closestDistance)
			{
				%closestDistance = %d;
				%closestObject = %obj;
			}
         }
    }
	%closestObject.safeDelete(); // do whatever you want with the closest object
}

-Aaron Fehlen
www.GetCleanGames.com

#1
11/21/2013 (7:12 pm)
To simplify a little:
function findClosestEnemy(%object)  
{  
    %list = myScene.getSceneObjectList();  
    %count = %list.count;  
    %closestDistance = 1000;  
    %closestObj = 0;  
  
    for( %i = 0; %i < %count; %i++ )  
    {  
         %obj = myScene.getObject( %i );  
           
         if( %obj.SuperClass $= "enemySuperClass" ) // filter out just the classes you want  
         {
            // There is a console function to get the distance between
            // two vectors (points):
            %pos1 = %obj.getPosition();
            %pos2 = %object.getPosition()
            %d = Vector2Distance(%pos1, %pos2);
              
            if(%d < %closestDistance)  
            {  
                %closestDistance = %d;  
                %closestObject = %obj;  
            }  
         }  
    }  
    %closestObject.safeDelete(); // do whatever you want with the closest object  
}
#2
11/21/2013 (11:00 pm)
I guess this is for T2D?
For T3D you'd just do a container search.
#3
11/24/2013 (6:45 pm)
Was about to say the exact same thing.