Distance between 2 squares in a 2d grid
BlitzMax Forums/BlitzMax Programming/Distance between 2 squares in a 2d grid
| ||
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. |
| ||
distance from x1,y1 to x2,y2: d = sqr((x2-x1)^2+(y2-y1)^2) |
| ||
function dist(x1#,y1#,x2#,y2#) distance# = sqr((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) return distance end function |
| ||
Great - thanks for your help Jesse and andy_mc! I knew there would be an easy maths answer! Much appreciated! |
| ||
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. |
| ||
Thanks Dave! |
| ||
thanks GFK I didn't realise that. I looked at the code and thought ^2 looked neater and that mine looked messy. |
| ||
Do a compare between the time taken to do 10 mil "^2" against 10 mil "N * N" and you'll drop your chin. |
| ||
Thanks everyone - working perfectly. |
| ||
@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. |
| ||
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 |