0
$\begingroup$

If I create a cube, the origin is originally at the center of mass. I know how to move the origin to the center of one of its faces using the interface, but how can I do the same thing via Python?

$\endgroup$
2
$\begingroup$

Bmesh script

This can be done similarly by using me.transform(T) with a translation matrix T. I have used an edit mode bmesh as it is simple to set the active face interactively before running script.

  • Get the local coordinate of the face center.
  • Subtract it from all coordinates, effectively making face center (0, 0, 0) or origin.
  • Move the object globally to reflect the local transform of the origin.

Script and Origin to Selected 2.80 addon available here https://blender.stackexchange.com/a/134460/15543

enter image description here Addon from link above, same result as script below

import bpy
from mathutils import Vector
import bmesh

context = bpy.context
ob = context.edit_object
me = ob.data
bm = bmesh.from_edit_mesh(me)

f = bm.faces.active
if f:
    o = f.calc_center_median()
    bmesh.ops.translate(bm,
           verts = bm.verts,
           vec = -o,
           )
    bmesh.update_edit_mesh(me)
    me.update()           
    # move the object globally to reflect
    mw = ob.matrix_world
    t = mw @ o - mw @ Vector()
    mw.translation += t

Since mw @ Vector() is essentially mw.translation the last line could be

     mw.translation = mw @ o        

Related: Set origin to bottom center of multiple objects

$\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.