I'm no developper but I managed to create a function that adds a specific keyframe on an object in Python.
It goes in 4 steps :
- check for animation data on the object (if none, create some)
- check for fcurve on the desired parameter (if none, create some)
- create the keyframe
- set the interpolation and easing for the keyframe
Blender NEEDS proper animation data and fcurve in order to add keyframes, any less and he'll look at you funny, spamming errors in the console.
Here's the code, with the 2 functions that handles the animation_data and fcurve check, and an example of the function in use :
def create_animation_data(target, name):
if target.animation_data == None:
target.animation_data_create()
target.animation_data.action = bpy.data.actions.new(name=name)
def create_fcurve(target, data_path, id):
fcurve = target.animation_data.action.fcurves.find(data_path=data_path, index=id)
if fcurve == None:
fcurve = target.animation_data.action.fcurves.new(data_path=data_path, index=id)
return fcurve
def set_kf_object(obj, data_path="location", id=2, val=0, frame=0, interpolation="BEZIER", easing="EASE_IN"):
#if no data, create animation data, new action, and new fcurve
create_animation_data(obj, data_path)
#store the fcurve
fcurve = create_fcurve(obj, data_path, id)
#insert the keyframe
key = fcurve.keyframe_points.insert(frame=frame,value=val)
#set interpolation and easing
key.interpolation = interpolation
key.easing = easing
#create a location keyframe on the Z axis, with a value of 1, at frame 36
#set the interpolation to 'CUBIC' and the easing to 'EASE_OUT'
cube = bpy.data.objects['Cube']
set_kf_object(cube, "location", 2, 1, 36, "CUBIC", "EASE_OUT")