# How to detect the distance between two edges (2D sprites)

2D - orthographic camera setup.

In Unity I have created one sprite object which is a rectangle (320 x 480) and I have created several other sprites (128 x 128 each) arranged in a circle around the rectangle.

If I determined a line from the center of the rectangular sprite to the centre of one of the square sprites, how can I detect at which vector(s) the line crosses the edge of each sprite so I can then determine the distance between those two points.

Math is a four letter word to me :)

Help

First, note that this isn't really a Unity question (as there's nothing Unity-specific about it). I'm sure you'll get some good answers here, but for this sort of question you might have as good or better luck on a general game development forum such as gamedev.net.

Anyway, computing the shortest distance between two axis-aligned rectangles isn't too difficult. There are really only two cases you have to consider: the first case is when each box lies fully within a 'corner' Voronoi region of the other box, and the second case is when they don't (in other words, the inverse of the first case).

Here's an example of the first case:

``````----
|  |
----

----
|  |
----

``````

In this case, the closest points are the box corners corresponding to the regions in question, and the shortest distance is the distance between those two points.

Here's an example of the second case:

``````----
|  |  ----
|  |  |  |
----  |  |
----

``````

In this case the shortest distance is the perpendicular distance between the closest edges (there is no unique pair of closest points).

The test itself then reduces to classifying one box in relation to the other to determine which Voronoi region(s) of the other box it intersects, and then computing the distance accordingly. The implementation can be a little involved due to the number of specific cases that have to be handled, but the algorithm itself is fairly straightforward.