Jump to content
  • Advertisement
Sign in to follow this  
cyric74

Efficient Distance Calculation?

This topic is 4884 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm currently using:
public static double GetDistance( ref float x1, ref float x2, ref float y1, ref float y2 )
{
	return Math.Sqrt( ( x1 - x2 )*( x1 - x2 ) + ( y1 - y2 )*( y1 - y2 ) );
}

I call this function many, many, many times per second server-side on my 2D space sim. The number of calls grows exponentially for each player that joins the server, so my question is, am I doing this the best way? Is there a cheat to get around doing it so much? Thanks, Cyric

Share this post


Link to post
Share on other sites
Advertisement
Not really, if you are having performance issues with a 2D space sim you should probably be looking at the bigger picture. There may be some other areas you can improve performance on, quadtrees perhaps? i don't know what is causing the problems but i'm sure there are other areas that you should think about optimising first.

The only trick with distances that i can think of is that if you are just comparing distance, you can compare the distances squared which avoids using the square root function. But you probably already knew that.

Share this post


Link to post
Share on other sites
One optimization that can often be done is to simply not do the square root. Use this when all you care about is comparing two distances to each other to see which one is larger. In this situation, the square root is absolutely useless, as it doesn't change the result of the comparison.

[edit]Me.Slow == true[/edit]

Share this post


Link to post
Share on other sites
Quote:
Original post by DevLiquidKnight
to increase speed u can remove the square root and work with higher values [smile]

They won't necessarily be higher: sqrt(x) > x is true for any x < 1.0

Share this post


Link to post
Share on other sites
I would suggest returning float (not double) and inlining it. A good compiler should eliminate the common sub expressions without creating the 2 extra variables.

I always...when in doubt cheat by looking at what the compiler actual does by examining the output .asm or .cod files.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!