Get closest point on 2D perimeter using Bounds

I’m using the Bounds.ClosestPoint to get the closest point on bounds but when inside the bounds you just get the current spot but I want to keep getting a point on the perimeter.

Can anyone throw me the calculations for that?

heh. interesting.

I can't think of a way to shortcut it,
so you'd need to find the shortest distance to each edge yourself.  

Note that Bounds is an Axis-Aligned Bounding Box,
which means the edges are parallel to the X and Y axes,
which simplifies finding the distance from a point to an edge.

okay, this actually works. there was another error in my example as well, but I’ve tested this.

Vector3 finder(Vector3 p, Bounds b)
{
    // I'll assume the 2D aspect of this is X and Y, and ignore Z.

    Vector3[] edgePoints = new Vector3[4];

    // point on left edge
    edgePoints[0].x = b.min.x;
    edgePoints[0].y = Mathf.Clamp(p.y, b.min.y, b.max.y);
    edgePoints[0].z = b.center.z;

    // point on right edge
    edgePoints[1].x = b.max.x;
    edgePoints[1].y = Mathf.Clamp(p.y, b.min.y, b.max.y);
    edgePoints[1].z = b.center.z;

    // point on bottom edge
    edgePoints[2].x = Mathf.Clamp(p.x, b.min.x, b.max.x);
    edgePoints[2].y = b.min.y;
    edgePoints[2].z = b.center.z;

    // point on top edge
    edgePoints[3].x = Mathf.Clamp(p.x, b.min.x, b.max.x);
    edgePoints[3].y = b.max.y;
    edgePoints[3].z = b.center.z;

    // now find the closest.

    float closestSqrDist = -1; // value doesn't matter.
    int closestIndex = -1; // value doesn't matter.
    for (int n = 0; n < 4; ++n)
    {
        float sqrDist = (edgePoints[n] - p).sqrMagnitude;
        if ((n == 0) || (sqrDist < closestSqrDist))
        {
            closestSqrDist = sqrDist;
            closestIndex = n;
        }
    }

    Vector3 closestPointOnEdgeOfBoundingBox = edgePoints[closestIndex];

    return closestPointOnEdgeOfBoundingBox;
}