0
$\begingroup$

I have a list of objects like this [bpy.data.objects["Text.002], bpy.data.objects["Text.003], bpy.data.objects["Text.005], bpy.data.objects["Text.007]] how can I sort them by their distance from a point like for example p =(0, 0, 0)?

I've tried to calculate the distance from two points in the 3d space using the origin and the point coordinates, but then how can I sort the objects?

$\endgroup$
1
$\begingroup$

There are a number of ways to sort lists in python. Here is one using lambda.

import bpy
from mathutils import Vector
# some list of objects (taken from q)
objects = [bpy.data.objects["Text.002"],
           bpy.data.objects["Text.003"],
           bpy.data.objects["Text.005"],
           bpy.data.objects["Text.007"]]
# sort by location from (0, 0, 0)
objects.sort(key=lambda o: o.location.length)
# sort by visual location from (0, 0, 0)
# eg objects moved by constraint / parenting etc.
objects.sort(key=lambda o:
             o.matrix_world.to_translation().length)

v = Vector((1, 2, 3))
# sort by distance from v
objects.sort(key=lambda o:
             (o.matrix_world.to_translation() - v).length)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.