# Get Closest point between a Box 3D and a Point I have a point A (x, y, z), and a Box: Center (x, y, z), Size (Width, Height)

How to get the closest point in the box from the point A ?

In Unity I can create a bound, and I can find the non-rotated position like that:

Bounds bounds = _mesh.bounds;
Vector3 closestPoint = bounds.ClosestPoint(pointA);


But then If the bound is rotated, the result is not correct. So I have 2 options:

Find the way to rotate my closestPoint from the pivot. Find the math formula myleft.

If someone can help ! thanks.

EDIT: here a video: the red point is the one find with bound.ClosestPoint the yellow point is the one find with:

Vector3 closestPointInverse = _currentTarget.InverseTransformPoint(closestPoint);


https://youtu.be/RMRRtSaJv8w

I have also tryed to do my own rotateFromPivot function:

public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles)
{
return Quaternion.Euler(angles) * (point - pivot) + pivot;
}


When I use it, I get the same result with the InverseTransformPoint method.

• Did you try first rotating the point into the mesh's coordinate space with transform.InverseTransformPoint? – DMGregory Sep 29 '19 at 13:52
• I have edited my question: yes I have, see the result in the video – Ugo Hed Sep 29 '19 at 14:18

## 2 Answers

Note that I said "first" not "after" - you're using the transform method backwards.

Vector3 ClosestPointOnMeshOBB(MeshFilter meshFilter, Vector3 worldPoint) {
// First, we transform the point into the local coordinate space of the mesh.
var localPoint = meshFilter.transform.InverseTransformPoint(worldPoint);

// Next, we compare it against the mesh's axis-aligned bounds in its local space.
var localClosest = meshFilter.sharedMesh.bounds.ClosestPoint(localPoint);

// Finally, we transform the local point back into world space.
return meshFilter.transform.TransformPoint(localClosest);
}


you should use colliders and raycast. tray to make a box collider for you box mesh. then cast a ray from point to center of box.

  void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit))
{
print(hit.point);

}
}
}


hit.point is nearest point t you empty object or point.