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
Lightly optimized C# alternative (although there should probably be some tolerance when comparing doubles against 0). I also recommend creating some kind of Rect or Point extension methods for these.
public static class GeometryUtils
{
public static double Distance(Point point, Rect rect)
{
var xDist = MinXDistance(point, rect);
var yDist = MinYDistance(point, rect);
if (xDist == 0)
{
return yDist;
}
else if (yDist == 0)
{
return xDist;
}
return Math.Sqrt(Math.Pow(xDist, 2) + Math.Pow(yDist, 2));
}
private static double MinXDistance(Point point, Rect rect)
{
if (rect.Left > point.X)
{
return rect.Left - point.X;
}
else if (rect.Right < point.X)
{
return point.X - rect.Right;
}
else
{
return 0;
}
}
private static double MinYDistance(Point point, Rect rect)
{
if (rect.Bottom < point.Y)
{
return point.Y - rect.Bottom;
}
else if (rect.Top > point.Y)
{
return rect.Top - point.Y;
}
else
{
return 0;
}
}
}