Sunday, March 10, 2013

2D Wraparound World

I figured I would share a finding I had while working on a project. For those of you who have attempted to code a representation of a wraparound map (2D torus) using a 1 or 2D array, you may have found the experience quite challenging to get operating smoothly. I was trying to find a more elegant solution when I stumbled upon the following formula:


sqrt(min(|x1 - x2|, w - |x1 - x2|)^2 + min(|y1 - y2|, h - |y1-y2|)^2)

Where the two points are (x1, y1) and (x2, y2);
w and h are the width and height;
min and sqrt are minimization and square root functions, respectively.

With that the process is absurdly easy.

Note: If you just need relative distance for a comparison, don't bother using the square root.


Function courtesy of:
http://stackoverflow.com/questions/2123947/calculate-distance-between-two-x-y-coordinates/2123977#2123977

No comments:

Post a Comment

A place in which to share your thoughts...