Find point on line given x and z coordinates

Hey guys, I’m trying to figure out how to find the closest point on a line in 2D(x and z) space, and then find the same point but in 3D space. Right now, I’m using the following function:

//tA and tB are the points of the line
//the function finds the closest point to tPoint on the line
function ClosestPointOnLine(tA : Transform, tB : Transform, tPoint : Transform)
{
	var vA : Vector3 = tA.position;
	var vB : Vector3 = tB.position;
	var vPoint : Vector3 = tPoint.position;

    var vVector1 = vPoint - vA;
    var vVector2 = (vB - vA).normalized;
 
    var d = Vector3.Distance(vA, vB);
    var t = Vector3.Dot(vVector2, vVector1);
 
    if (t <= 0) 
        return vA;
 
    if (t >= d) 
        return vB;
 
    var vVector3 = vVector2 * t;
 
    var vClosestPoint = vA + vVector3;
 
    return vClosestPoint;
}

The function works fine, if I want to find the actual closest point. However, like I said before, I want to find the closest point in 2D(x and z) space, and then convert that point to it’s 3D correspondent that lies on the line. Is there anyway to do this? If my question is still unclear, another way to phrase it is: “How do you find the point on a line given the x and z coordinates?”

Thanks in advance!

The equation for a line defined by a vector (expanded to the individual coordinates) is

x(t) = tvx + x0
y(t) = t
vy + y0
z(t) = t*vz + z0

Solving for t in, say, the first equation, we get

t = ( x(t) - x0 ) / vx

and plugging that into the equation for y:

y(t) = ( x(t) - x0 ) * vy / vx + y0

You can do a similar thing for z(t).

Thus, given just the x or z component, the point on the line is distinct, as long as vx or vz (respectively) are non-zero. If they are both zero, then there are infinitely-many points with those x/z coordinates.

If I understand your question correctly, you can process this as 2D by setting the ‘Y’ coordinates to for both vA and vB to the same value (like 0) before you do your calculations. You can project that back onto the line by figure out the percentage the closest point is between vA and vB and finding that percentage in the 3D line. Assuming vClosestPoint is calculated 2D and lies between vA2D and vB2D (the 2D end points), you can do something like:

var fraction = vVector3.magnitude/(Vector3.Distance(vA2D, vB2D);
vClosestPoint3D = Vector3.Lerp(vA, vB, fraction);