You can use the api:
double distance = mobile1.GetDistanceToSqrt(mobile2);
Anyway, if you want to compare the distance against some fixed value, rather use a power-of-two of the fixed value since square root calculations are quite expensive.
So if the original code looked like:
Code:
public static int CalculateDistance( Mobile from, Mobile target )
{
int distance = Math.Sqrt( Math.Pow( from.X - target.X, 2 ) + Math.Pow( from.Y - target.Y, 2 ) );
return distance;
}
....
if(CalculateDistance( m1, m2 ) > 7)
{
DoSomething();
}
Then the optimized code would look like:
Code:
public static int CalculateDistanceSansSqrt(Mobile from, Mobile target)
{
int dx= from.X - target.X;
int dy= from.Y - target.Y;
return (dx*dx) + (dy*dy);
}
if(CalculateDistanceSansSqrt( m1, m2 ) > ( 7*7 )/*49*/)
{
DoSomething();
}
Without the square root it turns out to be like 3.5 times faster.