Adventure Game Studio

AGS Support => Advanced Technical Forum => Topic started by: Bernie on Fri 04/11/2005 14:59:53

Title: Finding the closest character (SOLVED)
Post by: Bernie on Fri 04/11/2005 14:59:53
I'm trying to detect which character is the closest one to the player. I have a Distance(char1, char2) function returning the distance in pixels between two characters so far. I suppose it will come in handy here.

Basically, I'd like to make a GetClosestTo(char) function but have no idea where to start. I'd appreciate any ideas or pointers.
Title: Re: Finding the closest character
Post by: DoorKnobHandle on Fri 04/11/2005 15:14:57
You'd need to loop through all other characters and check their distance.

This is some code, that should work (although untested), but it could probably be improved somehow.


function GetClosestTo ( Character *Origin )
{
int result;

int charid = 0;

while ( charid < GetGameParameter(GP_NUMCHARACTERS, 0, 0, 0) )
// loop through all characters
{
if ( (character[charid].ID != Origin.ID) && (character[charid].Room == Origin.Room) )
// skip the origin character and characters not in current room
{
if ( Distance ( Origin, character[charid] ) < result ) // function described below
// if the distance between the characters are smaller
// than what we had before
{
// then store the new value
result = Distance ( Origin, character[charid] ); // function described below
}
}

// keep on searching
charid++;
}

// now return the result
return result;
}


Hope this is right and works. I am sure it will set you off in the right direction though!

Edit by strazer:

Added * and GetGameParameter

Btw, the "Distance" function:


function Distance(Character *char1, Character *char2) {
  int a = char1.x - char2.x; // get x-distance between characters
  int b = char1.y - char2.y; // get y-distance between characters
  return FloatToInt(Maths.Sqrt(IntToFloat((a*a) + (b*b)))); // calculate direct distance between characters (pythagoras)
}


Edit 2:

Added Pumaman's fix.
Title: Re: Finding the closest character
Post by: Bernie on Fri 04/11/2005 15:24:09
Haha, that was fast! This gave me a good idea for my own function. Thank you very much! :)
Title: Re: Finding the closest character (solved)
Post by: Pumaman on Fri 04/11/2005 22:10:33
In the loop, you should probably also make sure that the character is in the same room as the one you're testing.