Transform origin locally and object globally
To set the origin of an objects mesh to the global location of the scene cursor while maintaining the global location of the vertices, calculate the local coordinate of cursor, transform the mesh by subtracting it from all vert coordinates.
Then move the object back by the vector difference of starting global location (matrix world translation) and cursor location.
Test script: run in object mode.
import bpy
from mathutils import Matrix
context = bpy.context
scene = context.scene
ob = context.object
mw = ob.matrix_world
imw = mw.inverted()
me = ob.data
origin = scene.cursor.location
local_origin = imw @ origin
me.transform(Matrix.Translation(-local_origin))
mw.translation += (origin - mw.translation)
Note this will however move other objects that share the mesh.
For an edit mode version see
Setting mesh's origin in python (2.8)
transform()does nothing in Edit Mode (you could conditional use the bmesh module to translate the edit mesh). You might wanna useobj.matrix_world.translation += new_origininstead of.location. Not sure what you concern is about local coordinate @zeffii? – CodeManX Aug 16 '15 at 19:11.location? – zeffii Aug 16 '15 at 19:21new_origin? I tried several ways, such asnew_origin = [ 0.0, 0.0, -3.0 ]but I getTypeError: bad operand type for unary -: 'list'I want to shift the origin by -3 on my object's local Z axis, while geometry stays put relative to the world. Thanks. – Mentalist Dec 21 '20 at 05:24