3
$\begingroup$

I'm trying to use python to loop through objects in a specific way.

I have a grid of objects, evenly spaced apart:

enter image description here

I wan't to loop through them, to make changes. starting form the upper left, going row > column. I need the value of the row and column, as well as access to any object at any coridantes. I'm thinking that this would best be achieved by a 2D array [row][column], containing the objects.

pseudo-code:

for rows of objecs
    for objects in line with current row head //rowhead= left most object in the row
         //Do stuff

For testing:

$\endgroup$
4
$\begingroup$

Did not test this yet:

import bpy

COL_COUNT =  8 # number of columns
ROW_COUNT = 12 # number of rows

objects = bpy.data.groups['group_name'].objects[:]

# no cmp function
# use round to circumvent floating point precision errors
key_x = lambda o: round(o.location.x, 2)
key_y = lambda o: round(o.location.y, 2)

objects.sort(key=key_y, reversed=True) # from top to bottom
objects.sort(key=key_x)

for i, obj in enumerate(objects):
    col = i  % COL_COUNT
    row = i // COL_COUNT

    #do something with obj

See Sorting HOW TO from the official documetation for more information. The most relevant part is:

Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

To retrieve the object for a given row and column calculate the index:

index = row * COL_COUNT + col
obj = objects[index]

I.e. for ROW_COUNT = 2 and COL_COUNT = 4 the objects are tagged like this:

0 1 2 3 
4 5 6 7

For the second row and the third column the index is 1 * 4 + 2 = 6. (zero based indices!)

$\endgroup$
7
  • $\begingroup$ Testing now... :D $\endgroup$ – GiantCowFilms Feb 28 '15 at 20:33
  • $\begingroup$ Ah, yes. It sorts objects, not vectors, so i added o.location.y $\endgroup$ – pink vertex Feb 28 '15 at 20:35
  • $\begingroup$ How would I access somthing, say one row up and 3 to the left?, inside the loop $\endgroup$ – GiantCowFilms Feb 28 '15 at 20:36
  • $\begingroup$ You can build a nested list / array or calculate the index. The index should be row * COL_COUNT + col (starting with index 0) $\endgroup$ – pink vertex Feb 28 '15 at 20:46
  • $\begingroup$ I'm still confused, could you add that in a bit more detail to the answer? $\endgroup$ – GiantCowFilms Feb 28 '15 at 20:47

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.