Skip to main content
Share Your Experience: Take the 2024 Developer Survey
1 of 2
Markus von Broady
  • 36.9k
  • 3
  • 31
  • 101

Your confusion comes from the fact, that you think that you're rotating first by 90° around the Y axis, and then by -90° around the X axis. This is not what actually happens. What you're actually doing is changing the XY components of the rotation_euler property. The order in which you do this, doesn't matter.

If you modify the euler rotation XYZ components a hundred times, Blender doesn't store a list of those changes. It's just that, you updated the rotation values. When Blender renders a frame, it only rotates (up to) 3 times, in the order specified here:

So for the default XYZ order, Blender will first rotate around the X axis, then around Y axis, and finally around Z axis.

Why does it work the way you expect in the viewport, then? Because rotating in viewport is actually rotating, and after each rotation, the euler components are recalculated - it's not a direct and simple change of the euler rotation components. The script equivalent is creating a transformation matrix and applying that transformation matrix on the object, but because, just like with rotation order, there's also a matrix component order (translation before rotation), the easiest way to do this is to take only the object's euler rotation, convert it to matrix, apply other rotation matrices on it, and finally set the euler back on the object, this way at least you don't have to learn matrix (de)composition (not that it's hard).

import bpy
from bpy import context as C
from math import radians
from mathutils import Euler

ob = C.object
mat = ob.rotation_euler.to_matrix().to_4x4()
rot_value = radians(90)  # convert degrees to radians
y_rot = Euler((0, rot_value, 0))  # default order is XYZ
x_rot = Euler((-rot_value, 0, 0))
y_mat = y_rot.to_matrix().to_4x4()
x_mat = x_rot.to_matrix().to_4x4()
mat = x_mat @ y_mat @ mat  # read from right to left, first apply y_mat, then x_mat
ob.rotation_euler = mat.to_euler()
Markus von Broady
  • 36.9k
  • 3
  • 31
  • 101