Finding the closest character (SOLVED)

Started by Bernie, Fri 04/11/2005 14:59:53

Previous topic - Next topic

Bernie

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.

DoorKnobHandle

#1
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.

Code: ags

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:

Code: ags

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.

Bernie

Haha, that was fast! This gave me a good idea for my own function. Thank you very much! :)

Pumaman

In the loop, you should probably also make sure that the character is in the same room as the one you're testing.

SMF spam blocked by CleanTalk