I want to rotate my object to its nearest global axis with python. For example if the rotation of the object is more towards +x global, then the object rotation should snap to global +x rotation. Hope you all get it what I want to achieve. I don't have any code to show because couldn't figure it out how to start logic with.


1 Answer 1


Snap closest local to global rotation.

enter image description here Example of use, object with some arbitrary rotation, can see the local axes from the widget and the global axis from navigation widget, rotates in this case such that Z axes match

The columns of the 3x3 rotation matrix of the world matrix of an object is its unit vector global axis alignment.

Find the minimum angle between any and the global axes.

Create a rotation matrix from the difference between the vectors with minimal axis and transform the original.

import bpy
from mathutils import Matrix
from bpy import context

ob = context.object
mw = ob.matrix_world.copy()
R = mw.to_3x3().col
I = Matrix.Identity(3)

diffs = [locl.angle(globl) for locl, globl in zip(R, I)]
idx = diffs.index(min(diffs))

M  = (Matrix.Translation(mw.translation) @ 
      R[idx].rotation_difference(I[idx]).to_matrix().to_4x4() @
ob.matrix_world = M @ ob.matrix_world
  • $\begingroup$ Hi, I tried your code but it didn't have any effect to the rotation of the object. Nothing happened. Is there anything I need to do after executing this code? I tried it in console also but didn't have any effect in the rotation. $\endgroup$
    – Me BMan
    Aug 27, 2020 at 17:31
  • $\begingroup$ Added an example of usage in 2.8+ if you are using prior will need to replace @ with * (See blender.stackexchange.com/questions/129473/… ) If it is an edit mode rotation you are after see something like blender.stackexchange.com/questions/63506/… $\endgroup$
    – batFINGER
    Aug 27, 2020 at 17:45
  • $\begingroup$ Hi, it's working when I do it as a new script. but not when I add it to my custom script. I am figuring it out, why it's not working. I will get back here when I make it work. $\endgroup$
    – Me BMan
    Aug 27, 2020 at 18:18
  • $\begingroup$ Hi, now the code is working in my script, thanks very much. However After executing the code, lets say in your example, the resultant z rotation is -114, can we round that to -90?. I want them to be exactly 0, 90, 180, -90, or -180, whichever is nearest $\endgroup$
    – Me BMan
    Aug 28, 2020 at 5:02
  • $\begingroup$ I am currently rounding the result to the nearest 90 with the following code: Click here to view Code $\endgroup$
    – Me BMan
    Aug 28, 2020 at 7:24

You must log in to answer this question.

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