Blender: Object Rotation With Python
Date: 2021-10-19 | blender | python | rotation |
Overview
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: 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:
- First we
import bpy
which is the Blender Python library that allows us to interact with Blender- We also grab
math
and pull inList
for use later
- We also grab
- 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!
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.