# Intersection Of Line and Rectangle in 2D

). 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:

http://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! ::- )

-
Is the shooting line really infinite in both directions? Both your test and the linked method would count a hit if the enemy is directly behind the shooter. This could be a problem. – Rahul Mar 5 '11 at 18:45
In my case, the enemy can't be behind the shooter, so it's ok ::- D. Thanks for the tip though! – Axonn Mar 5 '11 at 18:57

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$.