1
$\begingroup$

I'm writing a python script for animation in Blender and I'm looking for a way to insert keyframes automatically.

So far I have:

import bpy 
import mathutils as m 
import math
import random

armature = bpy.data.objects['Armature']
curves = armature.animation_data.action.fcurves

def add_curve(): 

    action = bpy.data.actions.new(name = 'Test')
    curves = action.fcurves

    keyframes = [0,10,30] # defining keyframes for insertion
    for c in curves: 

        for k in keyframes: 
            c.keyframe_insert( data_path = ??)
            # Is there another method ?

Thanks !

$\endgroup$

1 Answer 1

1
$\begingroup$

You can find the data paths by right-clicking on the property and choosing 'Copy Data Path'. This gives you something like pose.bones["Bone.001"].rotation_euler.

With those you can call keyframe_insert directly on the armature object:

for ai in range(3): armature.keyframe_insert('pose.bones["Bone.001"].rotation_euler', ai)

This creates a keyframe for array indices 0, 1, and 2, for X, Y, and Z angles. If you want to use Quaternions, make sure you also use array index 4.

The keyframe_insert function will create a keyframe with the current value of the property (in this case the rotation); if you want to store another value, first change the property itself. You can also pass frame=f if you want to store the current value at a different frame.

By calling bpy.data.actions.new(name = 'Test') you always create a new action, which may not be what you want. Calling keyframe_insert directly on the armature will automatically create a new action if needed, so that's quite handy.

For more info, see the documentation for keyframe_insert.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .