# Tutorial :How to calculate the 3D line segment of two rectangles?

### Question:

I am looking for a fast way to calculate the line segment of two given rectangles in 3D. For instance, each 3D rectangle is defined by its four vertices.

A solution in any reasonable programming language will do.

### Solution:1

Based on Aaron's answer, which I believe contains an error:

1. Turn the two rectangles into two planes (just take three of the four vertices and build the plane from that).
2. Intersect the two planes to get an infinite line (*).
3. Intersect this line with the bounding lines of the first rectangle.
4. Intersect result of 3 with the bounding lines of the second rectangle.

If you omit step 4, then you get a false intersection when first rectangle intersects the second rectangle's plane but not the rectangle itself. Example:

``rectangle1=[(-1,-1,0),(-1,1,0),(1,1,0),(1,-1,0)]    rectangle2=[(0,50,50),(0,50,40),(0,40,40),(0,40,50)]  ``

Plane1 is z=0, plane2 is x=0, their intersection is the y axis, which intersects rectangle1 at 1 and -1. The rectangles do not intersect, though.

(*) If the planes overlap, the rectangles' intersection can still be a line, but it's a rather nasty case.

### Solution:2

You'll need to combine three common 3D operations:

1. Turn the two rectangles into two planes (just take three of the four vertices and build the plane from that).

2. Intersect the two planes to get an infinite line (see here).

3. Intersect this line with the bounding lines of the first rectangle. You should get two intersections which are the end points of the line segment you seek.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »