# Line intercept a rectangle

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

## Recommended Posts

Hi, If I have a rectangle, (a,b,c,d) and a line AB goes thru the rectangle. How can I calculate where the line will meet the rectangle A' and A"? And in the case where the line does not 'exit' the rectangle, (CD)? I am developing in C++ but that shouldn't matter to convert any other languages. Many thanks in advance. FFMG

##### Share on other sites
Simplest way would be to test the line against each of the 4 edges (line segments).

Theres a line line intersection description here http://ozviz.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/

##### Share on other sites
bool intersect(float p, float d, float min, float max, float& tenter, float& texit){    if(fabs(d) < 1.0E-6f)        return (p >= min && p <= max);    float t0 = (min - p) / d;    float t1 = (max - p) / d;    if(t0 > t1) { float temp(t0); t0 = t1; t1 = temp; }    if(t0 > texit || t1 < tenter) return false;    if(t0 > tenter) tenter = t0;    if(t1 < texit) texit = t1;    return true;}bool intersect(const float* min, const float* max, const float* p, const float* d, float* penter, float* pexit){    float tenter = 0.0f, texit = 1.0f;    if(!intersect(p[0], d[0], min[0], max[0], tenter, texit)) return false;    if(!intersect(p[1], d[1], min[1], max[1], tenter, texit)) return false;    //if(!intersect(p[2], d[2], min[2], max[2], tenter, texit)) return false; // for 3D    penter[0] = p[0] + d[0] * tenter;    penter[1] = p[1] + d[1] * tenter;    //penter[2] = p[2] + d[2] * tenter; // for 3D    pexit[0] = p[0] + d[0] * texit;    pexit[1] = p[1] + d[1] * texit;    //pexit[2] = p[2] + d[2] * texit; // for 3D    return true;}

##### Share on other sites
d is (b - a), aka

d[0] = b[0] - a[0];
d[1] = b[1] - a[1];
d[2] = b[2] - a[2];

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

• 10
• 9
• 9
• 11
• 11
• ### Forum Statistics

• Total Topics
633680
• Total Posts
3013304
×