- Home /
How to find the closest point on a line to another line
This is for a 3D project. The goal is to place an object on a line at the closest point to another line starting at the main camera's position which goes in the direction of the main camera's forward vector. I have 2 empty GameObjects marking the start and end positions of a line. How can I find the closest position on that line to the line which passes through the main camera?
Answer by AaronBacon · 4 days ago
Assuming I'm understanding you right, you want to find the shortest line that can be drawn that connects a point on one line to a point on another.
I would say the most efficient way is likely to do a kind of binary search, which is a sort of controlled bruteforce. What I mean by that is that assuming you have a start and end point for both lines, you can split both lines in half and then do a check for the shortest distance between the 4 midpoints (using Vector3.distance). So say you have Line A and Line B, you would find that these 2 halves are closest together:
⠀
⠀
You then Discard the halves that were furthest, moving the start and end point to the new location, and repeat the process:
⠀
⠀
You repeat this 10, 20 or however many times until you believe you have a small enough range that the player can't possibly get more precise (Say, within 0.001 of the actual shortest positions). A Limitation of a 2D diagram is that the shortest line above will always be at the ends unless they intersect, but in 3D space, it's the same principle, just get a pair of segments small enough and draw a line between their midpoint.
As for the actual implementation, you can get a point a certain percent along a line using something like
public Vector3 GetPointPercent(Vector3 startPoint,Vector3 endPoint, float percent)
{
return startPoint + (percent * (endPoint-startPoint));
}
Where percent is a decimal between 0 and 1, so 0.1 would give you a point 10% along a line. Without knowing exactly how your code works I think that's all the help I can give you, let me know if you have any further questions.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Looping through vector3 list slow 1 Answer
Punching objects (C#) 1 Answer
I want to create an interactive right analog MouseLook? 0 Answers