1
$\begingroup$

I want to add a camera from my scene using python. I followed the answer and it created the camera but I am not being able to change the focal length. I even tried using this answer but the focal length remains the same (as default = 50).

def setupCamera(scene, c):
    pi = math.pi

    scene.camera.rotation_euler[0] = c[0] * (pi / 180.0)
    scene.camera.rotation_euler[1] = c[1] * (pi / 180.0)
    scene.camera.rotation_euler[2] = c[2] * (pi / 180.0)

    scene.camera.location.x = c[3]
    scene.camera.location.y = c[4]
    scene.camera.location.z = c[5]

    return

scene = bpy.data.scenes["Scene"]
config = list([69.1, 1.6, 38.9, 7.22, -6.94, 4.95])
bpy.ops.object.camera_add()
cam = bpy.data.objects['Camera']
cam.rotation_mode = 'XYZ'
scene.camera = cam

# Changing focal length
bpy.data.cameras[0].lens = 9.0

setupCamera(scene=scene, c=config)

I have the links to answer but I cannot figure out why the focal length is not being changed to 9.0 ?

$\endgroup$
2
$\begingroup$

You are not modifying the correct camera. When you call bpy.ops.object.camera_add(), the newly created camera becomes the new active object. You can get it with bpy.context.object. You need to modify that camera.

scene = bpy.context.scene
bpy.ops.object.camera_add()
cam = bpy.context.object
cam.rotation_mode = 'XYZ'
scene.camera = cam

# Changing focal length
cam.data.lens = 9.0

config = [69.1, 1.6, 38.9, 7.22, -6.94, 4.95]
setupCamera(scene=scene, c=config)
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.