# Is possible to calculate the shortest distance between two geometry objects via python?

I need to add new geometry to my scene and it should fit inside a large box without any intersections.

Is it possible to calculate the shortest distance between two geometry objects in space, and check if the objects are intersecting each other via python?

• Sounds possible, but please define your requirements a bit more. What exactly you want to achieve? Do you want to calculate the distance between the bounding boxes or the distance of the center points? Can you share your code with us? An Image would also be helpful to understand your issue. Be aware: asking multiple questions is not allowed - for the ASCII part, the code of this addon: github.com/p2or/blender-vfxtoolbox could help you. – p2or Dec 22 '14 at 13:55
• Short answer is: 2 objects have intersection or not, Long answer is: Distance 'X' between minimal of face/edge/point of 2 objects. bankfotek.pl/image/1832980 – bardzo Dec 22 '14 at 19:30
• @bardzo Please edit your question with this additional information to reopen it. :) – p2or Dec 22 '14 at 19:43
• mathutils.geometry should help. distance_point_to_plane or intersect_point_line would be the starting point. – sambler Dec 24 '14 at 11:25

To get the distance between two objects use this formula.

$$d = \sqrt{\left(x_2-x_1\right)^2+\left(y_2-y_1\right)^2+\left(z_2-z_1\right)^2}$$

Then the python code is as follow. Comments are included in the code to help you understand what is going on.

import bpy
from math import sqrt

lst = []  # create list to store the location info

for obj in bpy.context.selected_objects:  # iterate over the selection NOTE: two object should be selected
lst.append(obj.location)  # populate the lst with the location info

# calulate the distance of the two objects
distance = sqrt((lst[0][0] - lst[1][0])**2 + (lst[0][1] - lst[1][1])**2 + (lst[0][2] - lst[1][2])**2)

# display the distance
print(distance)

• With vector math, included in blender, there is no reason to ever use the Euclidean formula as above. (obj1.matrix.world.translation - obj2.matrix_world.translation).length is the global distance between the origins of two objects obj1 and obj2 – batFINGER Nov 2 '19 at 11:03

The lines of the cube sides, the actual closest point might be between any two arbitrary places along those 2 edges, not necessarily just the corners. The origins of the objects are also not relevant (unless they're spheres, which they're not).

Given the above I think this is a better place to start:
https://math.stackexchange.com/questions/2213165/find-shortest-distance-between-lines-in-3d

• Add some other reference, maybe a quotation, in case the link you posted expired, got broken or the question is closed or whatever. – Lukasz-40sth Nov 26 '20 at 10:25