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

2 Answers 2

6
$\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$
0
$\begingroup$

ORIGIN TO CURSOR in edit mode

obj = context.active_object
loc = context.scene.cursor.location
me = obj.data
mw = obj.matrix_world

#move verts "back" (in prevision of next operation)
local = mw.inverted() @ loc 
ml = Matrix.Translation(-local)
bm = bmesh.from_edit_mesh(me)                                
bm.transform(ml)
bmesh.update_edit_mesh(me)

#move origin and verts
t = loc - mw @ Vector()
mw.translation += t 
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .