Getting array of Keyframe points in Blender

4.6k Views Asked by At

Hi i got a script im working on and its not working out as well as I want it to This is what I got so far

import bpy
def Key_Frame_Points(): #Gets the key-frame values as an array.

    fcurves = bpy.context.active_object.animation_data.action.fcurves

    for curve in fcurves:

        keyframePoints = fcurves[4].keyframe_points # selects Action channel's axis / attribute

        for keyframe in keyframePoints:

            print('KEY FRAME POINTS ARE  @T ',keyframe.co[0])         
            KEYFRAME_POINTS_ARRAY = keyframe.co[0]

    print(KEYFRAME_POINTS_ARRAY)

Key_Frame_Points()

When I run this its printing out all the keyframes on the selected Objects as I wanted it to. But the problem is that I cant for some reason get the Values its printing into a variable. If you run it and check the the System concole. its acting odd.Like as in its printing out the Values of the Keyframed object.But when I ask it to get those values as an array, its just printing out the last frame.

Here is how it looks like briefly

enter image description here

1

There are 1 best solutions below

3
sambler On

I think what you want to do is add each keyframe.co[1] to an array which means you want to use KEYFRAME_POINTS_ARRAY.append(keyframe.co[1]) and for that to work you will need to define it as an empty array outside the loop with KEYFRAME_POINTS_ARRAY = []

Note that keyframe.co[0] is the frame that is keyed while keyframe.co[1] is the keyed value at that frame.

Also of note is that you are looping through fcurves but not using each curve.

for curve in fcurves:
    keyframePoints = fcurves[4].keyframe_points

By using fcurves[4] here you are reading the same fcurve every time, you probably meant to use keyframePoints = curve.keyframe_points

So I expect you want to have -

import bpy

def Key_Frame_Points(): #Gets the key-frame values as an array.
    KEYFRAME_POINTS_ARRAY = []
    fcurves = bpy.context.active_object.animation_data.action.fcurves

    for curve in fcurves:
        keyframePoints = curve.keyframe_points
        for keyframe in keyframePoints:
            print('KEY FRAME POINTS ARE frame:{} value:{}'.format(keyframe.co[0],keyframe.co[1]))
            KEYFRAME_POINTS_ARRAY.append(keyframe.co[1])
    return KEYFRAME_POINTS_ARRAY

print(Key_Frame_Points())

You may also be interested to use fcurves.find(data_path) to find a specific curve by it's path.

There is also fcurve.evaluate(frame) that will give you the curve value at any frame not just the keyed values.