Calculating distance between two X,Y coordinates

Posted by Umopepisdn on Stack Overflow See other posts from Stack Overflow or by Umopepisdn
Published on 2011-01-02T11:04:55Z Indexed on 2011/01/02 11:53 UTC
Read the original article Hit count: 177

Filed under:
|
|
|
|

I am writing a tool for a game that involves calculating the distance between two coordinates on a spherical plane 500 units across. That is, [0,0] through [499,499] are valid coordinates, and [0,0] and [499,499] are also right next to each other.

Currently, in my application, I am comparing the distance between a city with an [X,Y] location respective to the user's own [X,Y] location, which they have configured in advance.

To do this, I found this algorithm, which kind of works:

Math.sqrt ( dx * dx + dy * dy );

Because sorting a paged list by distance is a useful thing to be able to do, I implemented this algorithm in a MySQL query and have made it available to my application using the following part of my SELECT statement:

SQRT( POW( ( ".strval($sourceX)." - cityX ) , 2 ) + POW( ( ".strval($sourceY)." - cityY ) , 2 ) ) AS distance

This works fine for many calculations, but does not take into account the fact that [0,0] and [499,499] are kitty-corner to one another.

Is there any way I can tweak this algorithm to generate an accurate distance, given that 0 and 499 are adjacent?

Thanks, -Umo

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql