0

I have a program where the user can place two boxes on the screen. They can be placed anywhere and I already fixed a function to get the coordinates of x2, x1, y2 and y1 of both of the boxes. Now when the user has placed both boxes I want to draw a line between the middle of one of the sides on box1 to the middle of one of the sides of box2. I would like to take into account the shortest distance between two sides. So that the line that is drawn is always drawn between the sides of the two boxes which would result in the shortest line.

At a point like this I wish I had paid more attention to math in school. Anyone able to help me out? This is for a web application and I am using javascript.

3
  • please add a small graphic for illustration, are the boxes rotated or in right angle ...? Commented Feb 16, 2016 at 8:13
  • need the size of the boxes too to calculate the distance, and are the points x1,x2,y1,y2 are the centre coordinates of the boxes or the top-left points
    – Roy
    Commented Feb 16, 2016 at 8:19
  • You can use shortest path algorithm, and then based on that co-ordinates you can draw a line. refer : en.wikipedia.org/wiki/Shortest_path_problem
    – Avinash
    Commented Feb 16, 2016 at 8:25

1 Answer 1

2

Start by determining potential anchor points of both boxes (left, right, top, or bottom edge). You can do a simple check for that, e.g.:

The left edge is a potential anchor point iff the other box' center x-coordinate is smaller than the current box' smaller x-coordinate.

The bottom edge is a potential anchor point iff the other box' center y-coordinate is greater than the current box' greater y-coordinate.

And so on...

After this, you have a list of candidates for both boxes. The actual anchor points can be calculated as the edge's center (( (edgeLeft + edgeRight) / 2, (edgeTop + edgeBottom) / 2)). Now, you need to check, which combination results in the shortest line. Iterate every candidate:

for each candidate1 in candidates of box 1
    for each candidate2 in candidates of box2
        ...

Now check if the combination results in an intersection. E.g. if candidate1 is the left edge and candidate2 has a greater x-coordinate, there is an intersection. Skip the combinations that result in an intersection.

From the other combinations, calculate the length of the line (actually the squared length: (candidate1.x-candidate2.x)^2 + (candidate1.y-candidate2.y)^2). Remember the shortest one and you've got your optimal connection line.

Since you have only 4 anchor points per box, resulting in 16 possible combinations, you might as well skip the candidate search and test all edges for intersection.

You can also fuse the candidate search and intersection test (resulting in a candidate combination search). This lets you pick viable combinations, where it may be easier to test for intersections.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.