# How to set origin points of multiple objects to a corner of their bounding boxes with Python?

So, I’m new to scripting in Blender but I do have a project which requires me to change the origins of all the meshes to minimum X, maximum Y and minimum Z coordinates of their bounding boxes so the left-down corner. A project consists of several meshes and it’s really repetitive. If it’s possible I would love to know how.

• Hi. I hope you don't mind my edit. Do you need the bounding boxes of the objects to be in global space or in local spaces of the objects? Commented May 23, 2019 at 5:48

First member of bounding box coordinates

The local coordinates of the 8 corners of the bounding box can be found via

bbox = [Vector(b) for b in o.bound_box]


ordered such that the bottom left hand corner is the zeroth element.

Python console code on default cube

>>> bbox = [Vector(b) for b in C.object.bound_box]
>>> for i, v in enumerate(bbox):
...     i, v
...
(0, Vector((-1.0, -1.0, -1.0)))
(1, Vector((-1.0, -1.0, 1.0)))
(2, Vector((-1.0, 1.0, 1.0)))
(3, Vector((-1.0, 1.0, -1.0)))
(4, Vector((1.0, -1.0, -1.0)))
(5, Vector((1.0, -1.0, 1.0)))
(6, Vector((1.0, 1.0, 1.0)))
(7, Vector((1.0, 1.0, -1.0)))


Test script run on selected objects in edit mode (v2.8) Subtract the LHC from all local coordinates. Globally move the object to reflect the change in origin. Note on re-reading your question, might want to use index 3

Edit. Made this a lot more robust. Since any or all of the selected mesh objects may share the same mesh, only want to set the origin of the mesh once, and globally shift each object using the adjusted mesh. For this a collections.defaultdict is used with the mesh as a key, and a list of objects using that mesh the values.

import bpy
from mathutils import Vector, Matrix
from collections import defaultdict
context = bpy.context

meshobs = defaultdict(list)
for o in context.selected_objects:
if o.type == 'MESH':
meshobs[o.data].append(o)

for me, obs in meshobs.items():
o = obs[0]
bbox = [Vector(b) for b in o.bound_box]
lhc = bbox[0]
T = Matrix.Translation(-lhc)
me.transform(T)
for o in obs:
o.matrix_world.translation = o.matrix_world @ lhc


Related

Setting mesh's origin in python (2.8)

Set origin to bottom center of multiple objects

• When I was about 10, I was in a geography lesson. The teacher had drawn a circle on the board, with an arrow through it. "This is the Earth,", he said, "and this is North, which is at the top." I stuck my hand up eagerly : "Not necessarily, sir!".. for which I was unceremoniously removed from the classroom and made to stand in a corner of the hall outside.... I mustn't do that again... Commented May 23, 2019 at 8:05
• Was it chalk on a blackboard? Please feel free to elaborate if you think answer is "not necessarily so". Did have 2 where i meant 3 re minx, maxy, minz., which will ensure all vert coords are x and z >= 0 and y <= 0. Commented May 23, 2019 at 10:17