Essay - Published: 2021.10.19 | blender | python | rotation |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
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.
Here's the source code we'll be looking at:
import bpy
import math
from typing import List
# docs: https://docs.blender.org/api/current/bpy.ops.mesh.html#bpy.ops.mesh.primitive_cube_add
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:
bpy.ops.mesh.primitive_cube_add(
size=size,
calc_uvs=True,
enter_editmode=False,
align='WORLD',
location=location,
rotation=rotation,
scale=scale,
)
def main():
add_cube(location=[0.0, 0.0, 0.0])
new_cube = bpy.context.object
new_cube.name = '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)
main()
And a walkthrough of the code:
import bpy which is the Blender Python library that allows us to interact with Blender
math and pull in List for use lateradd_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 Pythonmain() function is where we start creating objects
new_cube.rotation_euler to set the rotation of the object (note these are in radians!)The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.