I have a 3D rectangle, with 4 points (x,y,z)
And I have a player, who can be anywere (inside the rectangle, outside, not even in the plane, in the corner...).
I would like to get the closest point in that rectangle, to my player. The most efficient way
I have already a struct who can say the closest point to a line:
public struct ExtLine
{
public readonly Vector3 A;
public readonly Vector3 B;
public readonly Vector3 Delta;
public bool noGravityBorders;//if I want to return true only if player is in the boundary
public ExtLine(Vector3 a, Vector3 b, bool _noGravityBorders)
{
A = a;
B = b;
Delta = b - a;
noGravityBorders = _noGravityBorders;
}
public Vector3 PointAt(double t) => A + (float)t * Delta;
public double LengthSquared => Delta.sqrMagnitude;
public double LengthLine => Delta.magnitude;
public Vector3 ClosestPointTo(Vector3 p)
{
//The normalized "distance" from a to your closest point
double distance = Project(p);
if (distance < 0) //Check if P projection is over vectorAB
{
if (noGravityBorders)
return (ExtUtilityFunction.GetNullVector()); //an extention who give me an "null vector", not useful here
return A;
}
else if (distance > 1)
{
if (noGravityBorders)
return (ExtUtilityFunction.GetNullVector());
return B;
}
else
{
return A + Delta * (float)distance;
}
}
public double GetLenght()
{
return (LengthLine);
}
public double Project(Vector3 p) => Vector3.DotProduct(Delta, p - A) / LengthSquared;
}
And a struct who can say the closest point to a plane:
public struct ExtPlane
{
public Vector3 Point;
public Vector3 Direction;
public ExtPlane(Vector3 point, Vector3 direction)
{
Point = point;
Direction = direction;
}
public bool IsAbove(Vector3 q) => Vector3.DotProduct(q - Point, Direction) > 0;
public Vector3 Project(Vector3 randomPointInPlane, Vector3 normalPlane, Vector3 pointToProject)
{
Vector3 v = pointToProject - randomPointInPlane;
Vector3 d = Vector3.Project(v, normalPlane.normalized);
Vector3 projectedPoint = pointToProject - d;
return (projectedPoint);
}
}
How can I manage to find my point ? Thanks for help !