Get closest Vector3 position from a GameObject and two Transforms (and the line inbetween them)

Hi,

I need to get a Vector3 inside the range between two Transforms, having both Transform as the limit position regarding a third GameObject floating aroung the scene.

I drew an example hoping it would help.

All those Cubes would be the same GameObject and it’s possible positions, I mean, it could be anywhere… but the closest V3 would be constrained inside the line between Transform 1 and Transform 2.

I’m working in C#, but if you have the answer in JS I don’t care, just need the logic or initial direction in how to solve this problem.

Thanks in advanced!

Basically what you need is to draw a perpendicular from a given point to a line. Here’s a function to do that (first solution that came to my head, this can probably be done more elegantly).

private Vector3 ClosestPoint(Vector3 limit1, Vector3 limit2, Vector3 point)
	{
		Vector3 lineVector = limit2 - limit1;

		float lineVectorSqrMag = lineVector.sqrMagnitude;

		// Trivial case where limit1 == limit2
		if(lineVectorSqrMag < 1e-3f)
			return limit1;

		float dotProduct = Vector3.Dot(lineVector, limit1 - point);

		float t = - dotProduct / lineVectorSqrMag;

		return limit1 + Mathf.Clamp01(t) * lineVector;
	}

The function takes two limiting points (as in your example), and the location of the floating object. It returns a point on the line between two limits that is closest to the floating object.

// input values
Transfrom a;
Transform b;
Transform gameobjects;

// output values
Transform closest = null;
Vector3 pos;

float minDist = float.PositiveInfinity;
Vector3 posA = a.position;
Vector3 posB = b.position;
Vector3 d = (posB - posA).normalized;
for(int i = 0; i < gameobjects.Length; i++)
{
    Vector3 p = gameobjects*.position;*

Vector3 v = p - posA;
Vector3 point = posA + Vector.Project(v, d);
float dist = (point - p).sqrMagnitude;
if (dist < minDist)
{
minDist = dist;
closest = gameobjects*;*
pos = point;
}
}
Untested but should work.
edit
It’s hard to tell from your drawing if an object that actually is close to the “ray” that your two transforms defines but it’s projected point is outside the line segment what distance you want to calculate.
One way would be to define two Planes which specifiy the ends of the line:
Plane p1 = new Plane(d,posA);
Plane p2 = new Plane(-d,posB);
Inside the for loop you would do:
Vector3 v = p - posA;
Vector3 point = posA + Vector.Project(v, d);
if (!p1.GetSide(p))
point = posA;
if (!p2.GetSide(p))
point = posB;
float dist = (point - p).sqrMagnitude;
// …
That way you get a capsule shape around your line.