2
$\begingroup$

I want to set keyframe interpolation 'CONSTANT' while setting a keyframe.

I have this, https://docs.blender.org/api/current/bpy.types.Keyframe.html

but I don't know where should I add the line in the code?

import bpy

obj = bpy.context.object

# set the keyframe at frame 1
obj.rotation_euler = (0, 0, 0)
obj.keyframe_insert(data_path="rotation_euler",index= 1, frame=1)

# set the keyframe at frame 24
obj.rotation_euler = (0, 6.28, 0)
obj.keyframe_insert(data_path="rotation_euler",index= 1, frame=24)
```
$\endgroup$

1 Answer 1

4
$\begingroup$

Using keyframe_insert automatically sets the curve handle type to 'BEZIER' as mentioned here.

Assuming you do use you're posted script:

import bpy

obj = bpy.context.object

# set the keyframe at frame 1
obj.rotation_euler = (0, 0, 0)
obj.keyframe_insert(data_path="rotation_euler",index= 1, frame=1)

# set the keyframe at frame 24
obj.rotation_euler = (0, 6.28, 0)
obj.keyframe_insert(data_path="rotation_euler",index= 1, frame=24)

There is no longer a direct reference to the action or key just created so lets find it.

# ensure the action is still available
if obj.animation_data.action:
    # and store it in a convenience variable
    my_action = bpy.data.actions.get(obj.animation_data.action.name)

Now we want to specifically find the fcurve related to the data_path used above

my_fcu = my_action.fcurves.find("rotation_euler", index=1)

And finally we can set the interpolation of the handles

# for all points
for pt in my_fcu.keyframe_points:
    pt.interpolation = 'CONSTANT'

# for a specific frame
frm = 24
pt = [pt for pt in my_fcu.keyframe_points if pt.co[0] == frm][0]
pt.interpolation = 'CONSTANT'
$\endgroup$
3
  • 1
    $\begingroup$ The default interpolation with keyframe_insert is actually always BEZIER, see eg T45189 (which also discusses OP's question). $\endgroup$
    – scurest
    Commented Apr 10, 2022 at 9:41
  • $\begingroup$ @scurest TY for correction $\endgroup$
    – Ratt
    Commented Apr 10, 2022 at 9:45
  • $\begingroup$ Wow the API indeed should be improved here. BTW, I think the "ensure the action is still available" would be way too defensive even if you had an alternative way to obtain the action (too defensive because the action simply is supposed to be there), but also you're avoiding the error just to get it on the next line my_fcu = my_action.fcurves... $\endgroup$ Commented Apr 10, 2022 at 10:31

You must log in to answer this question.

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