# Rotate an object around an axis using python script

I try to rotate and translate objects and then insert a keyframe by calling the function below:

def set_keyframe(frame_no, x, y, rotation_z, object_id):

# change frame
bpy.context.scene.frame_current = frame_no

# select the object
currentObject = bpy.data.objects[object_id]
currentObject.select = True

# translate and insert keyframe
currentObject.location.x = x
currentObject.location.y = y
currentObject.keyframe_insert('location')


I could manage to translate the object, however I couldn't find out how to perform the rotation operation. I am just trying to rotate around z axis. I tried to do it using the object's matrix_world in order to simultaneously translate and rotate the object, as suggested here and here. However, I couldn't manage it. Any help, which may not necessarily use the matrix_world, would be appreciated!

P.S. my objects are scaled.

If you don't want to manipulate matrix_world you have to check the rotation_mode of the object first and set the corresponding value accordingly.

import bpy
import math
import mathutils

obj = bpy.context.active_object
eul = mathutils.Euler((0.0, math.radians(45.0), 0.0), 'XYZ')

if obj.rotation_mode == "QUATERNION":
obj.rotation_quaternion = eul.to_quaternion()
elif obj.rotation_mode == "AXIS_ANGLE":
q = eul.to_quaternion()
obj.rotation_axis_angle[0]  = q.angle
obj.rotation_axis_angle[1:] = q.axis
else:
obj.rotation_euler = eul if eul.order == obj.rotation_mode else(
eul.to_quaternion().to_euler(obj.rotation_mode))

• I have just noticed that the issue was due to a constraint I previously defined. It didn't allow any rotation around z-axis. But thanks a lot for your reply, now I see how to do it without manipulating 'matrix_world' Jun 22 '15 at 13:22

same with matrices

import bpy
import math
import mathutils

obj = bpy.context.active_object
eul = mathutils.Euler((0.0, math.radians(45.0), 0.0), 'XYZ')
#eul.to_matrix is 3x3 but we need 4x4 to multiply with matrix_world
R = eul.to_matrix().to_4x4()
mw = obj.matrix_world
mw @= R