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?
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
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
mw @ Vector() is essentially
mw.translation the last line could be
mw.translation = mw @ o