Here is a solution in Java that returns true if a line segment (first 4 parameters) intersects a rectangle aligned on the axis (last 4 parameters). It would be trivial to return the intersection point instead of Boolean. It works by first checking to see if it is completely outside, otherwise using the linear equation y=m*x+b . We know that the lines that make up the rectangle are aligned along the axis, so checking is easy.
public boolean aabbContainsSegment (float x1, float y1, float x2, float y2, float minX, float minY, float maxX, float maxY) {
You can use a shortcut if the beginning or end of the segment is inside the rectangle, but it's probably best to just do the math, which will always return true if inside or both ends of the segment are inside. If you need a shortcut anyway, paste the code below after checking "completely outside".
NateS Aug 17 '13 at 20:20 2013-08-17 20:20
source share