I wrote a function to calculate the distance between two positions:
def distanceBetween(pos1, pos2): xDiff = pos2.x - pos1.x yDiff = pos2.y - pos1.y dist = Math.sqrt(xDiff**2 + yDiff**2) # self.say(dist) return(dist)
However, this seems to tax the system. If I use this function in Summit’s Gate, the Chrome Browser crashes. Even on my powerful desktop system.
I suggest using the following approximation:
def distanceBetween(pos1, pos2): xDiff = pos2.x - pos1.x yDiff = pos2.y - pos1.y if xDiff < 0 : xDiff = -xDiff if yDiff < 0 : yDiff = -yDiff if xDiff > yDiff : dist = xDiff + 0.33 *yDiff else : dist = yDiff + 0.33 *xDiff # self.say(dist) return(dist)
The answer returned is within 6% of the exact value and avoids the square and square root functions.
(Note: I see an old topic which says that you should be able to call distanceTo on other objects, but that didn’t seem to be working for me. I will re-investigate.)