0

I'd like to locate a object at (0,0,0) in the global coordinate system, but the object has its own coordinate system, such that bpy.context.object.location = (0,0,0) does not work:

Coordinate systems

How can I determine the offset to move the object to the global point of origin (0,0,0)?

frthjf
  • 395
  • 2
  • 14
  • 2
    related: http://blender.stackexchange.com/questions/24015/how-to-place-objects-on-the-center-of-the-ground-plane-via-python/24018#24018 – p2or Jan 18 '16 at 19:38
  • without origin_set(): http://blender.stackexchange.com/questions/35825/changing-object-origin-to-arbitrary-point-without-origin-set – p2or Jan 18 '16 at 19:49
  • @poor Thanks, this goes definitive in the right direction, I still don't have a working code, but I will continue to figure it out ... – frthjf Jan 18 '16 at 20:22
  • Glad I could help. What exactly is not working? – p2or Jan 18 '16 at 20:23
  • I did not recognize that the object dimensions are local coordinates too ... – frthjf Jan 18 '16 at 22:00

2 Answers2

1

Using the ideas of the proposed solution, this snippet does the offset calculation:

bpy.context.scene.update()

# determine minima of the object
min_x = min_y = min_z = 999999.0
for vertex in self.blender_object.data.vertices:
        # object vertices are in object space, translate to world space
        v_world = self.blender_object.matrix_world * Vector((vertex.co[0], vertex.co[1], vertex.co[2]))

        if v_world[0] < min_x:
            min_x = v_world[0]

        if v_world[1] < min_y:
            min_y = v_world[1]

        if v_world[2] < min_z:
            min_z = v_world[2]

# convert to world coordinates again
size = self.blender_object.matrix_world * self.blender_object.dimensions

offset = Vector((min_x +  size.x/2, min_y - size.y/2, min_z))

self.blender_object.location = self.blender_object.location - offset
frthjf
  • 395
  • 2
  • 14
  • Tested, works well! The only change for me is offset = Vector((min_x + size.x/2, min_y + size.y/2, min_z)). Also note in Blender 2.8 Matrix-Vector multiply is now expressed with '@' sign. – Dmitry Mikushin Jun 17 '20 at 21:54
1

You can also do this with three operators and no calculations (will certainly be faster than iterating over all vertices if you have a high-resolution mesh). That is if you don't mind that it will center your object's origin point.

import bpy
bpy.ops.object.mode_set( mode = 'OBJECT' ) # Make sure we're in object mode
bpy.ops.object.origin_set( type = 'ORIGIN_GEOMETRY' ) # Move object origin to center of geometry
bpy.ops.object.location_clear() # Clear location - set location to (0,0,0)
TLousky
  • 16,043
  • 1
  • 40
  • 72