20

I need to get the x,y,z values of an object as well as the bounding box through a script. So far I have the area and volume with the following code:

bm = bmesh.new()
bm.from_object(bpy.context.object, bpy.context.scene)
area = str(sum(f.calc_area() for f in bm.faces))
volume = str(bm.calc_volume())

I tried something like this for the bounding box:

bb = str(bm.dimensions())

or

bb = bpy.data.objects["test2-2"].dimensions

but neither have worked. As far as the x,y,z values go I'm stumped. Please let me know if you have any suggestions.

Thanks!

Alex Husarenko
  • 545
  • 2
  • 4
  • 10

2 Answers2

28

To include parenting and drivers, use this for the actual object location / origin:

ob = bpy.context.object

ob.matrix_world.translation # or .to_translation()

You can get the bounding box corners Object.bound_box in object-space and multiply by Object.matrix_world for world-space:

from mathutils import Vector
bbox_corners = [ob.matrix_world @ Vector(corner) for corner in ob.bound_box]
# bbox_corners = [ob.matrix_world * Vector(corner) for corner in ob.bound_box]  # Use this in V2.79 or older

Note that the bounding box is not axis aligned.

CodeManX
  • 29,298
  • 3
  • 89
  • 128
  • 2
    Starting from 2.8 TypeError: Element-wise multiplication: not supported between 'Matrix' and 'Vector' types: needs to be: bbox_corners = [ob.matrix_world @ Vector(corner) for corner in ob.bound_box] – oneiros Nov 05 '19 at 18:14
  • @oneiros I also encountered this error did you find any solution for it? – AvivSham Jan 28 '20 at 06:40
  • 1
    @AvivSham it's right there: bbox_corners = [ob.matrix_world @ Vector(corner) for corner in ob.bound_box] (change the asterisk * to an at symbol @) – CodeManX Jan 28 '20 at 13:01
18

Both location and dimensions are vectors, meaning they'll return a vector of three values (x, y, z). If you want to get only one axis, use:

bpy.data.objects['object_name'].location.x
bpy.data.objects['object_name'].location.y
bpy.data.objects['object_name'].location.z

The dimensions of the bounding box of that object:

bpy.data.objects['object_name'].dimensions.x
bpy.data.objects['object_name'].dimensions.y
bpy.data.objects['object_name'].dimensions.z

You can set the values by simply using obj.location.x = 5, or if you would like to set all three axes, you can do obj.location = (1, 2, 3)

Greg Zaal
  • 10,856
  • 3
  • 47
  • 86
  • 1
    If I try to use dimension.x in a driver variable, it doesn't recognize it as a valid data path. I have to write dimensions[0] to get the x value. – Max Kielland Oct 30 '14 at 19:31