public static Point getClosestPointOnRectangleBorderToPoint( ref Rectangle rect, Vector2 point )
{
// for each axis, if the point is outside the box clamp it to the box else leave it alone
var res = new Point();
res.X = Mathf.clamp( (int)point.X, rect.Left, rect.Right );
res.Y = Mathf.clamp( (int)point.Y, rect.Top, rect.Bottom );
// if point is inside the rectangle we need to push res to the border since it will be inside the rect
if( rect.Contains( res ) )
{
var dl = res.X - rect.Left;
var dr = rect.Right - res.X;
var dt = res.Y - rect.Top;
var db = rect.Bottom - res.Y;
var min = Mathf.minOf( dl, dr, dt, db );
if( min == dt )
res.Y = rect.Top;
else if( min == db )
res.Y = rect.Bottom;
else if( min == dl )
res.X = rect.Left;
else
res.X = rect.Right;
}
return res;
}