0
$\begingroup$

I'm trying to write a python script to programmatically assign location and rotation values to keyframes based on a csv file that I am ingesting and parsing. When I hardcode in the frame number and the z location value, the animation behave mostly correctly. When I try to programmatically assign those keyframes and z values from an ingested csv value, the keyframes are created but the z values are not assigned. I appreciate your insights and guidance.

Assigning values to keyframes directly

import bpy
import csv
import numpy as np

data = np.zeros(7)

location = []
    
bpy.data.objects['Cube'].select_set(True) # 2.8+

obj = bpy.context.object
obj.animation_data_create()
obj.animation_data.action = bpy.data.actions.new(name="MyAction2")

fcu_z = obj.animation_data.action.fcurves.new(data_path="location", index=2)

fcu_z.keyframe_points.add(12)

fcu_z.keyframe_points[0].co = 0, 0.0
fcu_z.keyframe_points[1].co = 10, 1.0
fcu_z.keyframe_points[2].co = 20, 2.0
fcu_z.keyframe_points[3].co = 30, 3.0
fcu_z.keyframe_points[4].co = 40, 2.0
fcu_z.keyframe_points[5].co = 50, 1.0
fcu_z.keyframe_points[6].co = 60, 0.0
fcu_z.keyframe_points[7].co = 70, 1.0
fcu_z.keyframe_points[8].co = 80, 2.0
fcu_z.keyframe_points[9].co = 90, 3.0
fcu_z.keyframe_points[10].co = 100, 2.0
fcu_z.keyframe_points[11].co = 110, 1.0

Assigning keyframes programmatically from a 12 line csv file

import bpy
import csv
import numpy as np

data = np.zeros(7)

path = 'filepath.csv'

location = []

with open(path, mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            line_count += 1
        location.append((row["\ufeffframe"], row["x"], row["y"], row["z"]))
        
        line_count += 1
    
bpy.data.objects['Cube'].select_set(True) # 2.8+

obj = bpy.context.object
obj.animation_data_create()
obj.animation_data.action = bpy.data.actions.new(name="MyAction2")

fcu_z = obj.animation_data.action.fcurves.new(data_path="location", index=2)

fcu_z.keyframe_points.add(12)

for i in range(line_count-1):
    fcu_z.keyframe_points[i].co = float(location[i][0]), float(location[i][3])
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.