- Home /
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!
Answer by Casiell · Aug 06, 2019 at 06:40 AM
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
Answer by Bunny83 · Aug 06, 2019 at 08:13 AM
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.
Your answer
Follow this Question
Related Questions
How to get vector X distance from point on Y angle? 4 Answers
Math Question : How to Get a Point on a Ray which is EXACTLY 5 units away from Vector3.Zero? 5 Answers
Maths: Given a point on a circle and a fixed length line. Find the next closest point on the circle. 2 Answers
Find center between 4 points 3 Answers
how do i keep a gameobject in between the union of 2 or more than 2 circles 0 Answers