Page 1 of 1

"advanced maths" in queries

Posted: Sat Dec 09, 2006 2:47 am
by Flamie
So heres the deal, in my code I have:

Code: Select all

$posx; //player's X position
$posy; //player's Y position
Now in my database, in my player table theres a posx and posy position.

Now I have a viewport of 550x350 pixels which is peg registered (player is always centered).
Now to grab the other players right now I do a simple query and grab all the players whos posx and posy are within that 550x350 rectangle around you.
One problem with that is that it doesnt return them in order of distance from you.
I was thinking of changing that query to order by distance, which would mean SQRT( ($posx - posx)^2 + ($posy - posy)^2), now heres my question:
is it ok to do a query where "distance" is less than 275, ordered by distance? Or would that slow down the query a lot?

Posted: Sat Dec 09, 2006 5:37 am
by onion2k
Keep your code as it is at the moment where you're only returning players within the viewport, but add the distance equation to the fields returned and order by it. That way you'll only be calculating the distance of visible players instead of all the players. Much more scalable.

Posted: Sat Dec 09, 2006 5:38 am
by Vikas Jayna
It certainly will add some overhead to the query as the computations will be done for every record in the result set and then the ordering would be done. What would be number of players within another players viewport at any given point of time? Unless this number is huge, there should be no issues with the query in terms of speed.