is there a easy formula to calculate this? i\'ve been working on some math but i can only find a way to calculate the distance directed to the center of the box, not direct
This is easy to achieve with dot products. In fact it has been answered in 3d already for the non axis aligned case.
https://stackoverflow.com/a/44824522/158285
But in 2D you can achieve the same
public struct Vector2 {
double X; double Y
// Vector dot product
double Dot(Vector2 other)=>X*other.X+Y*other.Y;
// Length squared of the vector
double LengthSquared()=>Dot(this,this);
// Plus other methods for multiplying by a scalar
// adding and subtracting vectors etc
}
The function to return the closest point
public Vector2 ClosestPointTo
(Vector2 q, Vector2 origin, Vector3 v10, Vector3 v01)
{
var px = v10;
var py = v01;
var vx = (px - origin);
var vy = (py - origin);
var tx = Vector2.Dot( q - origin, vx ) / vx.LengthSquared();
var ty = Vector3.Dot( q - origin, vy ) / vy.LengthSquared();
tx = tx < 0 ? 0 : tx > 1 ? 1 : tx;
ty = ty < 0 ? 0 : ty > 1 ? 1 : ty;
var p = tx * vx + ty * vy + origin;
return p;
}