Getting Rotation from World Matrix

I am not very familiar with how to work with the world matrix in python. I have been doing some reading on how they work, but still a little confused about how to find the world x, y, and z rotation.

Getting the location is easy enough

world_matrix = bpy.context.object.matrix_world
x_loc = world_matrix[0][3]
y_loc = world_matrix[1][3]
z_loc = world_matrix[2][3]

But rotation seems a bit more difficult. Sorry for the basic question, but can anyone point me in the right direction on how to find this information. Thanks.

Is there a reason why you aren’t using bpy.context.object.rotation_euler to get the object’s rotation?

That just returns the local rotation. I suppose I can just loop through all of the parent objects and accumulate the rotation. Is that the best way to do it?

Matrices don’t store Euler rotations; if you want to pull a Euler out of one, you’ll have to use some_matrix.to_euler(). Or follow Robert’s advice.

Oh nice. matrix.to_euler() was exactly what I was looking for. Thanks!

Right, that was my misunderstanding. You can find those helper functions in mathutils.Matrix in the API docs: https://docs.blender.org/api/current/mathutils.html#mathutils.Matrix.to_euler

The reason why you cannot get the rotation by accessing a specific component in the world matrix, is because the world matrix is the result of the multiplication of the translation, rotation and scale matrices. Each rotation around an axis require different components of the matrix to be set, not a singular one at a particular index. This answer on Stack Exchange for a different question shows how the world matrix is constructed.

3 Likes