Blender: Object Rotation With Python

2021.10.19 | 283 words |


In this post I’m going to give a brief overview of how to set object rotations and create keyframed object rotation animations using the Blender Python API.

Object Rotation in Blender with Python

Here’s the source code we’ll be looking at:

import bpy 
import math

from typing import List

# docs:
def add_cube(
        size: float = 1.0,
        location: List[float] = [0.0, 0.0, 0.0],
        rotation: List[float] = [0.0, 0.0, 0.0],
        scale: List[float] = [2.0, 2.0, 2.0]) -> None:

def main():
    add_cube(location=[0.0, 0.0, 0.0])
    new_cube = bpy.context.object = 'New Cube'

    # set static rotation
    new_cube.rotation_euler = [0, 0, math.radians(45)]

    # set keyframe rotation
    new_cube.rotation_euler = [0, 0, 0]
    new_cube.keyframe_insert(data_path='rotation_euler', frame = 1)
    new_cube.rotation_euler = [0, 0, math.radians(45)]
    new_cube.keyframe_insert(data_path='rotation_euler', frame = 30)


And a walkthrough of the code:

  • First we import bpy which is the Blender Python library that allows us to interact with Blender
    • We also grab math and pull in List for use later
  • We then define add_cube which is a helper function for instantiating a cube I wrote. I have describe this more and provide more helper functions in Blender: Create basic shapes with Python
  • The main() function is where we start creating objects
    • Here we create a cube at the origin (0, 0, 0)
    • We then grab that cube into a variable for easy access and set a recognizable name in the Editor
    • We can use new_cube.rotation_euler to set the rotation of the object (note these are in radians!)
    • Blender animations happen in keyframes which are basically snapshots of different states of an object at different times. By setting these, we can have Blender render the rest for us!

About the Ham

Hi I'm Hamilton - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus