#### Archived

This topic is now archived and is closed to further replies.

# Line Segment-Rectangle Intersection

This topic is 6194 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How can I determine if a line segment intersects a rectangle? What I am currently doing is breaking the rectangle into line segments and doing four seperate line segment-line segment intersection checks. Is there a better way?

##### Share on other sites
That seems like the best way there could be ... it works and it is simple! However, once you have tested that there are two intersections you could stop since the line can only intersect the rectangle in two places.

Good luck.

##### Share on other sites
here comes the code from my engine , use it wisely

///////////////////////////////////////////////////////////////
// ray / box intersection
bool RayBoxIntr( float x0,float y0,float z0,
float x1,float y1,float z1,
float ax,float ay,float az,
float bx,float by,float bz)
{

float t,px,py,pz,l,m,n;

l=x1-x0;
m=y1-y0;
n=z1-z0;

//////////////////////////////////////////////////////

t=(ax-x0)/l;

px=x0+t*l;
py=y0+t*m;
pz=z0+t*n;

if ( t>=0.0f && t<=1.0f )
if ( px>=ax && px<=bx )
if ( py>=ay && py<=by )
if ( pz>=az && pz<=bz )
return true;

t=(bx-x0)/l;

px=x0+t*l;
py=y0+t*m;
pz=z0+t*n;

if ( t>=0.0f && t<=1.0f )
if ( px>=ax && px<=bx )
if ( py>=ay && py<=by )
if ( pz>=az && pz<=bz )
return true;

//////////////////////////////////////////////////////

t=(ay-y0)/m;

px=x0+t*l;
py=y0+t*m;
pz=z0+t*n;

if ( t>=0.0f && t<=1.0f )
if ( px>=ax && px<=bx )
if ( py>=ay && py<=by )
if ( pz>=az && pz<=bz )
return true;

t=(by-y0)/m;

px=x0+t*l;
py=y0+t*m;
pz=z0+t*n;

if ( t>=0.0f && t<=1.0f )
if ( px>=ax && px<=bx )
if ( py>=ay && py<=by )
if ( pz>=az && pz<=bz )
return true;

//////////////////////////////////////////////////////////////

t=(az-z0)/n;

px=x0+t*l;
py=y0+t*m;
pz=z0+t*n;

if ( t>=0.0f && t<=1.0f )
if ( px>=ax && px<=bx )
if ( py>=ay && py<=by )
if ( pz>=az && pz<=bz )
return true;

t=(bz-z0)/n;

px=x0+t*l;
py=y0+t*m;
pz=z0+t*n;

if ( t>=0.0f && t<=1.0f )
if ( px>=ax && px<=bx )
if ( py>=ay && py<=by )
if ( pz>=az && pz<=bz )
return true;

//////////////////////////////////////////////////////

return false;
}

##### Share on other sites
As always , i''ve posted things too quickly, if you are looking for a ''solid'' axis oriented line / rectangle intersection this is
for you , for an arbitrary orientation things gets a little bit more complicated but not so mush, if you are trying to detect an
intersection beetween a ray and a ''wire'' rectangle the method you are working on is th correct one bye and have a good year

1. 1
2. 2
3. 3
4. 4
Rutin
15
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633724
• Total Posts
3013554
×