View Full Version : Line Intersecting a rectangle.

17-01-2007, 02:43 PM
Hi everyone,

I want to check if a line intersects with a rectangle so I can make a beam weapon for my game.

Does anyone have any nice little function or something?

something like..

TestLineIntersection( X1,Y1,X2,Y2 : integer; TestRect : trect ) : boolean;

once I've done this, I need to write a line pixel test routine against the image of the sprite in question and a quick bit of Bresenham's to tell me which pixels to test.

17-01-2007, 03:30 PM
I'm wondering if we've got something like this...


So I imagine that if I use the function described here to test each side of a box, it'll work against a line...

I know, it looks daft, me answering my own question, but if anyone's got a function ready rolled for this job, I'd still like to see it.

17-01-2007, 04:13 PM
When line intersects a rectangle it means that there are corners of the tested rectangle that are above and below the line.

The LineTestIntersection function can be like this:

1. Create line equation ax+b=y from x1,y1,x2,y2
a = (y2-y1 )/(x2-x1)
b = y1-a*x1
2. for each corner of the rect calculate d = ax + b - y
where x and y are coordinates of each corner
3. Check the signs of all four d's. If they are not the same then line intersects the rect, otherwise there is no intersection.

I hope you find it usefull.

17-01-2007, 08:27 PM
This could be a solution, but I think you don't want to use this:

The way I did it in NecroSPACE 1&2 and .S.C.A.G. is just to put hit points on my beam. this way I just checked if there was an intersection between a point and a rectangle. this way there an be more hits and one target, do more damage as it penetrates deeper.