View Single Post
Old 08-07-2008, 06:12 AM   #4 (permalink)
arul
Forum Expert
 
arul's Avatar
 
Join Date: Jan 2005
Location: Hic sunt leones ...
Age: 21
Posts: 1,289
Send a message via MSN to arul
Default

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.
__________________
Angels are falling the very last time, down they're burning in hate and decline, unfaithful and violent we're breaking the spell, we're god, we're scissor, in heaven and hell!

Last edited by arul; 08-07-2008 at 10:41 AM.
arul is offline   Reply With Quote