Sub topic 17
Keyframing with Python
This chapter assumes that you can select an object, change its transforms, and run code in Blender's Scripting workspace. A basic understanding of frames and keyframes is also assumed.
Python can create the same animation that you create manually in the 3D Viewport. The main method is keyframe_insert(). It stores the current value of a property at a specific frame.
Insert keyframes with a script
The following script animates the active object. It starts at the origin on frame 1 and moves two Blender units upward by frame 24.
import bpy
scene = bpy.context.scene
scene.frame_start = 1
scene.frame_end = 48
scene.render.fps = 24
obj = bpy.context.active_object
if obj is None:
raise RuntimeError("Select an object before running this script.")
obj.location = (0.0, 0.0, 0.0)
obj.keyframe_insert(data_path="location", frame=1)
obj.location = (0.0, 0.0, 2.0)
obj.keyframe_insert(data_path="location", frame=24)
scene.frame_set(12)
print("Current frame:", scene.frame_current)bpy.context.scene refers to the current scene. The frame_start and frame_end properties define the playback range. The render.fps property sets the frame rate.
bpy.context.active_object returns the object currently active in the interface. The location property contains the X, Y, and Z position. The data_path argument tells Blender which property to animate.
A keyframe stores all three location values because location is a vector. You can also keyframe one component:
obj.keyframe_insert(data_path="location", index=2, frame=1)Here, index=2 means the Z component. The indexes are X = 0, Y = 1, and Z = 2.
Between frames 1 and 24, Blender evaluates the stored values and generates the in-between motion. This process is called interpolation.
Change interpolation with Python
New keyframes usually use Bezier interpolation. This creates smooth acceleration and deceleration. To make motion travel at a constant rate, set each keyframe's interpolation to LINEAR.
import bpy
obj = bpy.context.active_object
action = obj.animation_data.action
if action is None:
raise RuntimeError("The active object has no animation action.")
for fcurve in action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = "LINEAR"An F-curve is Blender's animation data for one changing property. The X, Y, and Z location components normally use separate F-curves. An action groups the F-curves that belong to an object's animation.
The Dope Sheet remains useful after scripting. Open it to inspect the generated keyframes, move them, change their types, or retime the animation. Python creates the data, while Blender's animation editors provide visual control.
Exercise
How would you change the example so the object reaches Z = 5.0 on frame 48?
Show answer
Change the second assignment to obj.location = (0.0, 0.0, 5.0) and change its frame argument to 48.