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.
Snap closest local to global rotation.
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() @ Matrix.Translation(-mw.translation)) ob.matrix_world = M @ ob.matrix_world