Jump to content
  • Advertisement
Sign in to follow this  
FFMG

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.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!