Closest point on multiple lines?

So there are several answers for “find the closest point on a line”, but I’m having a time extrapolating that math to multiple lines. How would I find the closest point on any line from say, an array of lines? (Especially if that array might be dozens or even hundreds of lines)

Specifically what I’m trying to do is place objects alongside one of any number of road sections. Roads are interlocking, and each has a curb section that the player can place objects along. They could be hovering over any number of roads, along either side of the sidewalk - how do I find the correct closest one among all that noise? Thank you!

Can’t you just iterate over your road array, calculating closest point for each of them. Then calculate the distance for those points and choose the one that is closest to your player

If there are only hundreds of lines you probably just want to check each one like Casiell said. However you could also build a QuadTree and subdivide your space that way which will make lookups a lot faster. This CodingTrain video has a full explanation and example code (not in C# for Unity but in Javascript but the concept is the same) for how to implement a quadtree. Since you don’t have a point quad tree but an “object” quadtree the only difference would be the “contains” implementation which need to be an “intersect” instead. You can actually use Unity’s Bounds struct instead of the “Rectangle” class he creates.

Since your usecase seems to be road segments they most likely rarely change their position so a QuadTree might actually make sense for relatively low amounts ob objects as well.

The essential idea is that you calculate / create the bounds for each line segment and insert it into the quadtree. If the object overlaps a quadtree cell we have to insert it into that cell. Unlike the case for points, objects do have a size and can be part of two or more cells at the same time.