Closest point on a line?

Hi, I ran into another mathematical problem there…
I have a script setting up the equation for a straight 2D-line (y = k*x + t) passing through to points, but then I need another script to determine the point on this line which is closest to the player. I thought of somehow projecting a vector A onto a vector B, A being a vector going from the starting point of the line to the player’s position and B being a directional vector of the line.

Anyway, I couldn’t really figure out a way of how this can be done, is there a simple solution to this problem?:face_with_spiral_eyes:

This is just a matter of orthogonality. You need a slope which intersects your current grape at 90 degrees and passes through the point of interest. If k is fixed, then your slope is k and the perpendicular line would be -1/k. If k is not a fixed value, it’s kind of similar, but more complicated.

Okay, I just found a solution using Vector3.Project… Seems like I wasn’t searching for it long enough and askied for help to early…

But what’s really frustrating is the fact that your proposition involves exactly the same mathematical stuff I had in an exam last week. Maybe I should revise more frequently…:roll_eyes:

If you found a solution, you’re welcome to post it on the same page that you asked the question!

1 Like

It’s good the OP solved his problem. There is an elegant solution to a similar problem, for anyone looking to find the nearest point on a line segment between two points: http://forum.unity3d.com/threads/8114-math-problem?p=59715&viewfull=1#post59715

1 Like

I’m kind of racking my brain understanding how Vector3.Project can be used to find the point on a line closest to another point

Would you mind posting a snippet of your code that shows how to use this solution?

I asked the question some time ago, so i’m not entirely sure what code I was using, but the method wasn’t very reliable. In the end (as I refered to earlier), I just reused the stuff from my math lessons.

The easiest way to find the point on a line that’s closest to a specific point in space is to draw a line perpendicular to the other line, but passing through your point. We are looking for the closest point on that first line, so just check for an intersection between the two lines. That exact spot is the point you’re looking for.

I guess back then, I used a pretty complicated script that somehow ended up using Vector3.Project(). It must have given me some approximation of the correct result or I wouldn’t have done it that way, but I really suggest using the solution involving perpendicular lines passing through a point.

C# code

	static public float GetDistPointToLine(Vector3 origin, Vector3 direction, Vector3 point){
		Vector3 point2origin = origin - point;
		Vector3 point2closestPointOnLine = point2origin - Vector3.Dot(point2origin,direction) * direction;
		return point2closestPointOnLine.magnitude;
	}
1 Like