5
$\begingroup$

I am trying to animate the focal length of the camera, based on focal length information imported from a file. setting the focal length is no problem:

focal_length = 35
timeline_frame = 10
cam = bpy.data.cameras.new('Camera')
cam.lens = focal_length

after setting this value I want to insert a keyframe for the focal length. According to my intuition, I am looking for something like this:

cam.keyframe_insert(data_path = 'lens', frame = (timeline_frame))

(this code deosn´t work...) is there any way to get this to work?

$\endgroup$

3 Answers 3

1
$\begingroup$

Your code works fine. But note that you are adding a new camera data when you do bpy.data.cameras.new('Camera'). If there already is a Camera data, the new one you created will be named Camera.001. Make sure this camera data is assigned to your camera object.

Assigning the camera data to the camera object

$\endgroup$
1
$\begingroup$

The problem, as was in my case, is that you cannot do

cam.keyframe_insert(data_path = 'lens', frame = (timeline_frame))

if cam is an object, you have to take reference of the camera type, not the object, because the action regarding to lens animation is assigned to a camera type not object type.

bpy.data.objects["objectID"].keyframe_insert("lens") #DOESNT WORK
bpy.data.cameras["cameraID"].keyframe_insert("lens") #WORKS

the safer way if there is only one camara in scene (as batFinger pointed out) would be:

bpy.context.scene.camera.data.keyframe_insert("lens", frame = (timeline_frame))

$\endgroup$
3
  • 1
    $\begingroup$ cam = bpy.context.scene.camera.data is possibly the best way to get the camera data of the active camera object. Check that scene.camera is not None first. There is no guarantee using last line of answer code will be the correct camera data. Not sure they are ordered such that the last added is last in collection bpy.data.cameras[-1]. $\endgroup$
    – batFINGER
    Commented Jan 27, 2020 at 13:48
  • $\begingroup$ The order of bpy.data.cameras is alphabetcal. My guess is the error in question was adding new camera data object which was neither linked to object, and hence not the scene camera or any scene camera object. The keyframe would be added ok but would not show up in the UI unless you switched the data as shown in other answer. $\endgroup$
    – batFINGER
    Commented Jan 27, 2020 at 13:56
  • $\begingroup$ thank you batFinger i didn't noticed that bpy.data.cameras is alphabetical OO_OO XD $\endgroup$ Commented Jan 27, 2020 at 14:04
0
$\begingroup$

Notice: Camera focalLength's data_path is not "lens"!! It is "data.lens"!!

I waste a lot of time to find it out.

Blender version: 3.3

$\endgroup$

You must log in to answer this question.

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