• Create Account

# xissburg

Member Since 30 Apr 2005
Offline Last Active Nov 07 2012 12:52 PM

### #4992454Intersection Between 2D Ray and Rectangle Borders

Posted by on 21 October 2012 - 09:22 AM

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 codePoint 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]

PARTNERS