Toroidal-wrapping square map distance function

The smallest distance between two points on a square map whose edges wrap like a torus.

So there are two coordinates, x and y (I don’t have any idea what a 3D toroidal mapping would be like, but it’s intriguing, huh?).  Let’s say that x goes from 0 to w-1 (“width”), and y goes from 0 to h-1 (“height”).

We can consider x-distance and y-distance independent of each other.  (Let’s call them Δx and Δy.)

Let’s assume that the two x coordinates are x0 and x1, and also that x0≤x1.  There are two possible values for Δx: x1-x0 and (x0+w)-x1 (looping around).

The same argument holds for y0 and y1.  (Note that the two points could be (x0,y0) and (x1,y1), or they could be (x0,y1) and (x1,y0)—doesn’t matter!)


Δx = min(x1-x0, x0+w-x1)

Δy = min(y1-y0, y0+h-y1)

And finally, our standard Euclidean distance:

d = sqrt(Δx2 + Δy2)

Responses are currently closed.