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!