 # How to get the distance between two objects?

hello. im trying to get the distance between two objects, so that i can use it as a variable to scale objects/a collection based on their proximity to an empty. id be grateful for any suggestions.

You have to subract on position vector from the other and then get its length:

``````import bpy

myActive = bpy.context.active_object
mySel = bpy.context.selected_objects

loc0 = mySel.location
loc1 = mySel.location

length = (loc0 - loc1).length

print(length)
``````

This might fail if you have hierarchies because .location will then get the location of the object relative to its parent.
You have to use matrix_world.to_translation in that case:

``````import bpy

myActive = bpy.context.active_object
mySel = bpy.context.selected_objects

loc0 = mySel.matrix_world.to_translation()
loc1 = mySel.matrix_world.to_translation()

length = (loc0 - loc1).length

print(length)
``````
1 Like

your code works perfectly, but im struggling to make it use object names instead.
for example, Empty01 and Cube.
my code looks like this:
import bpy

myActive = bpy.data.objects[‘Empty01’]
mySel = bpy.data.objects[‘Cube’]

loc0 = mySel.location
loc1 = mySel.location

length = (loc0 - loc1).length

print(length)

ive tried a few ways of replacing it with object names, but i havnt been able to get it so far. its been a few months since i last did coding, so im afraid im very rusty. do you know the correct way?

Just for some short explanation:
Lets say you have 5 objects selected.

mySel in my script is defined as all selected objects.
This means that mySel is now a list with 5 things in it. Python lists start at 0 so the objects positions in the list range from 0 to 4.

mySel is the first object on this list.
mySel is the second object on this list
mySel is the third object on this list
and so on

loc0 = mySel.location
means that blender looks up the location of the first object on the list and saves it into the variable loc0

Anyway, if you want to do it by name you don’t need the list.

You can simply get the locations of the objects directly:

``````import bpy

loc0 = bpy.data.objects['Cube.003'].location
loc1 = bpy.data.objects['Cube.004'].location

length = (loc0 - loc1).length

print(length)
``````
1 Like

Good stuuf @Lumpengnom thank you so much for the explanation, i hadn’t realised it was a list. ive been able to get it working exactly how i want it now. i really appreciate all your help.

Apparently once Blender upgrades to python 3.8 it will be possible to us:

math.dist(point1, point2)

instead subtracting the two location vectors and then measuring the length of the resulting vector.