# Determine Whether Ray Intersects Given Rectangle

I'm building a city generator for my game and I want to ensure buildings are never placed in such a way that they overlap roads. Currently I have the system build the roads, then place buildings alongside those roads.

I have the beginning and end points of the roads as Vector3s (only using X and Z, Y is never considered for road/building placement). For buildings, I use the size of their Box Colliders to check if they can fit in a given space (with rotation and scale applied appropriately). I've done a fair amount of research for answers on lines intersecting planes, though they always seem to be incredibly hard to follow or just don't properly apply to my situation (such as determining if the line is coterminous or not). I simply need to know if the line at any point exists within the bounds of the building's rectangle. I do not need to know where or at what angle.

I also understand that my problem is essentially a 2D math problem, as I'm ignoring Y, and some of the 2D solutions I've seen to this would be extremely costly to do in city generation.

Any help would be greatly appreciated.

• Presumably you considered using BoxCollider.Raycast to cast a ray against the collision shape? Jul 19, 2020 at 21:11
• @DMGregory I had not, actually. I wasn't aware that was a thing! Seems like I could cast it from one end of the road to the other, see if it intersects with the current building's collider. Thanks for this idea! Jul 20, 2020 at 23:31
• If that solved your problem, you may want to post an answer showing how you solved it. Or click the checkmark to accept the answer below if it worked for you. Nov 12, 2021 at 1:02

You can consider the building's rectangle as 4 lines, as shown in this image:

Then you need the check if the road's line intersects any of the rectangle's lines. Here's another answer, which shows intersection between lines: https://stackoverflow.com/a/3746601/8715999