Sign in to follow this  
FFMG

Line intercept a rectangle

Recommended Posts

Hi, If I have a rectangle, (a,b,c,d) and a line AB goes thru the rectangle. Image Hosting 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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this