• Advertisement
Sign in to follow this  

Intersection Between 2D Ray and Rectangle Borders

This topic is 1899 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

Hello! I need to find this point, if someone could help...

[img]http://imageshack.us/a/img694/3699/questionnw.jpg[/img]
dir is always centered in rectangle.

Thanks ;-) Edited by hdlopesrocha

Share this post


Link to post
Share on other sites
Advertisement
lets say h and w are width and height of the rectangle
c is the center point.

1. Determine how far you can move:

d = min( h/2/abs(dir.y), w/2/abs(dir.x) );

2. Move:

x = c + d * dir

Share this post


Link to post
Share on other sites
You could use the tangent of the angle of the dir vector. Depending on the direction it is pointing, you use a different formula based on the angle of the diagonal of the AABB. I've came up with this:

[source lang="cpp"]
// WARNING: Untested code
Point Intersect(Point min, Point max, float alpha) // alpha is the dir vector angle
{
float beta = atan2(max.y - min.y, max.x - min.x); // AABB diagonal angle
float hw = (max.x - min.x)*0.5; // AABB width/2
float hh = (max.y - min.y)*0.5; // AABB height/2
float tanAlpha = tan(alpha);
if (fabsf(alpha) < beta) // right section
return Point(max.x, min.y + hh + tanAlpha*hw);
else if (fabsf(PI - alpha) < beta) // left section
return Point(min.x, min.y + hh - tanAlpha*hw);
else if (fabsf(PI*0.5 - alpha) < PI*0.5 - beta) // top section
return Point(min.x + hw + 1.f/tanAlpha*hh, max.y);
else if (fabsf(1.5f*PI - alpha) < PI*0.5 - beta) // bottom section
return Point(min.x + hw - 1.f/tanAlpha*hh, min.y);
else // should not happen o_ O
return WTF;
}
[/source]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement