Intersection Between 2D Ray and Rectangle Borders

Started by
2 comments, last by HenriqueRocha 11 years, 5 months ago
Hello! I need to find this point, if someone could help...

questionnw.jpg
dir is always centered in rectangle.

Thanks ;-)
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
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]
.
thanks ;-) problem solved!

This topic is closed to new replies.

Advertisement