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?
Asked
Active
Viewed 3,252 times
1
-
This might help you: https://blenderartists.org/t/modifying-object-origin-with-python/507305 – HikariTW May 15 '19 at 02:47
2 Answers
6
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
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
batFINGER
- 84,216
- 10
- 108
- 233
0
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
Uneconscience UneSource
- 394
- 1
- 9