Search code examples
pythonmath3d

Get distance from a point to the nearest box


I have a 3D space where positions are stored as tuples, eg: (2, 0.5, -4). If I want to know the distance between two points I just do dist = (abs(x1 -x2), abs(y1 - y2), abs(z1 - z2)) and if I want a radius distf = (dist[0] + dist[1] + dist[2]) / 3. Now I have boxes each defined by two min / max positions (eg: (-4 8 -16) to (4, 12, 6)) and I want to know the distance between my point to the closest one: What is the simplest way to know the distance to the closest face in all 3 directions, or 0 in case the position is inside a box? Just looking for the lightest solution that doesn't require numpy or libraries other than defaults like math since I'm not using those in my project.

This is my messy solution which should probably work but I'd like to know if there's anything better.

point = (8, 12, 16)
box_min = (-4, -4, -4)
box_max = (4, 4, 4)

box_center = ((box_min[0] + box_max[0]) / 2, (box_min[1] + box_max[1]) / 2, (box_min[2] + box_max[2]) / 2)
box_scale = (abs(box_max[0] - box_min[0]), abs(box_max[1] - box_min[1]), abs(box_max[2] - box_min[2]))
dist = (abs(box_center[0] - point[0]) + box_scale[0] / 2, abs(box_center[1] - point[1]) + box_scale[1] / 2, abs(box_center[2] - point[2]) + box_scale[2] / 2)

Solution

  • You can use (dx ** 2 + dy ** 2 + dz ** 2) ** 0.5 for calculating the distance:

    def _dist(A, B, C):
        dx = max(B[0] - A[0], 0, A[0] - C[0])
        dy = max(B[1] - A[1], 0, A[1] - C[1])
        dz = max(B[2] - A[2], 0, A[2] - C[2])
        return (dx ** 2 + dy ** 2 + dz ** 2) ** 0.5
    
    
    def _dist_b(A, B, C):
        dx = max(B[0] - A[0], 0, A[0] - C[0])
        dy = max(B[1] - A[1], 0, A[1] - C[1])
        dz = max(B[2] - A[2], 0, A[2] - C[2])
        return (dx, dy, dz)
    
    
    print(_dist((8, 12, 16), (-4, -4, -4), (4, 4, 4)))
    print(_dist_b((8, 12, 16), (-4, -4, -4), (4, 4, 4)))
    
    

    Prints

    14.966629547095765
    (4, 8, 12)