Find point along line

Hello.

I have a vector (A-B) and I have an object that is between those two points. I am trying to find the intersection point along A-B where that object would be at 90 degrees.

The rotation of the object as well as the direction of the A-B vector is not a factor, as long as the object is between the two points.

I may not be explaining that well so illustration below;

109840-untitled.png

I think I need vector3.project() but am not sure how I would use that here.

thanks in advance.

You can use Vector3.Project, indeed :

public Vector3 GetPositionOnSegment( Vector3 A, Vector3 B, Vector3 point  )
{
    Vector3 projection = Vector3.Project( point - A, B - A ) ;
    return projection + A ;
}

A little more verbose version of @Hellium’s answer. Also version constraining to endpoints.

    // a and b are points on the line. p is the point in question.
	Vector3 ClosestPoint (Vector3 a, Vector3 b, Vector3 p) {
		Vector3 ab = b - a;
		Vector3 ap = p - a;
		Vector3 ar = Vector3.Project (ap, ab);
		return a + ar;
	}
	
	// a and b are the endpoints of the line segment. p is the point in question.
	Vector3 ClosestPointConstrained (Vector3 a, Vector3 b, Vector3 p) {
		Vector3 ab = b - a;
		Vector3 ap = p - a;
		Vector3 ar = Vector3.Project (ap, ab);

		if (Vector3.Dot (ab, ar) < 0) {
			return a;
		}
		if (ar.sqrMagnitude > ab.sqrMagnitude) {
			return b;
		}
		return a + ar;
	}

Classic vector algebra problem, yay! :slight_smile:

You are basically looking for the nearest point to your object on a segment defined by points A and B.
I think the solution is the InverseLerp() of A, B with the position of your object, and then Lerp() A and B with that value:

// returns how far value is between vector ab. If length of ab is 0, returns float.NaN!
public static float InverseLerp (Vector3  a, Vector3 b, Vector3 t) {
    Vector3 aToB = b - a;
    Vector3 aToT = t - a;
    return Vector3.Dot(aToT, aToB) / aToB.sqrMagnitude; // vector magic! :D
}

public static Vector3 ClosestPointOnSegment(Vector3 point, Vector3 a, Vector3 b) {
    float t = InverserLerp(a, b, point); // maybe check here that your value is correct
    return Vector3.Lerp(a, b, t);
}

Probably there is a simpler solution, but I suck at vector algebra, I just happen to have this in my utilities library.