[Math] Intersection Of Line and Rectangle in 2D

geometry

). I'm working on a Flash game and I need to find when a shooting line intersects an enemy. The enemy's shape is rectangular. So far, I was thinking to test this like so:

  • Test if the shooting line intersects ANY of the lines composing the rectangle. BUT while the shooting line can be endless, I need to only validate an intersection if the shooting line ACTUALLY TOUCHES THE INSIDE of any of the rectangle's lines, meaning that the X/Y of the intersection point has to be along one of those lines.

I'm wondering if there is an easier method. Like, for example, the one they used here for a Triangle:

https://stackoverflow.com/questions/3590308/testing-if-a-line-has-a-point-within-a-triangle

Is this applicable to a Rectangle as well? If so, could you please explain a bit of the reasoning? ::- ). It's been a long time since I did any math, but I'm faithfully coming back to it now, because I want to continue developing games. Any help is greatly appreciated and will not be forgotten ::- D.

P.S.: Also, my games are freeware! ::- )

Best Answer

Yes, that solution would work! And I think it is quite clever.

One observes that a line $ax + by + c = 0$ in the plane defines two semi-planes: the points $(\overline{x}, \overline{y})$such that $a\overline{x} + b\overline{y} + c > 0$ and those for which $a\overline{x} + b\overline{y} + c < 0$.

The algorithm works because by substituting the coordinates of the vertices one finds in which semi-plane they lie. If some vertices lie in the upper semi-plane and some in the lower semi-plane then we must conclude that the line does intersect the polygon.