Distance between 2 squares in a 2d grid

BlitzMax Forums/BlitzMax Programming/Distance between 2 squares in a 2d grid

Matthew Smith(Posted 2010) [#1]
Hi,

Can anyone help me out with some quick maths.

I have a 2d grid (say 20x20 squares) and need to determine the distance (triangulate) between 2 particular squares.

I just need a direct value nothing too fancy like finding it's way around objects like A*

Thanks in advance.


Jesse(Posted 2010) [#2]
distance from x1,y1 to x2,y2:

d = sqr((x2-x1)^2+(y2-y1)^2)


andy_mc(Posted 2010) [#3]
function dist(x1#,y1#,x2#,y2#)
distance# = sqr((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
return distance
end function


Matthew Smith(Posted 2010) [#4]
Great - thanks for your help Jesse and andy_mc! I knew there would be an easy maths answer!

Much appreciated!


GfK(Posted 2010) [#5]
Its worth mentioning that andy_mc's code will be slightly quicker as multiplication is faster than doing ^2.

Also, if you need to check multiple distances and just find out which is nearest (without the need to know the actual distance) you can dispense with the Sqr() which will also speed things up a bit.


Matthew Smith(Posted 2010) [#6]
Thanks Dave!


andy_mc(Posted 2010) [#7]
thanks GFK I didn't realise that. I looked at the code and thought ^2 looked neater and that mine looked messy.


Kryzon(Posted 2010) [#8]
Do a compare between the time taken to do 10 mil "^2" against 10 mil "N * N" and you'll drop your chin.


Matthew Smith(Posted 2010) [#9]
Thanks everyone - working perfectly.


Jesse(Posted 2010) [#10]
@GFK, Andy_mc and Kryzon, Mine is faster sence I didn't put it in a function.

using exponents is slower but if you are so concerned about speed why use a function. it's a bigger speed hit than the exponent factor.


Foppy(Posted 2010) [#11]
As a side note, if a function is used, you can leave out the extra local variable and return the value right away, like this:
function dist(x1,y1,x2,y2)
    return(sqr((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)))
end function