Printing location data of camera fails

Hi Everybody

I’ve only a few days ago started to work with python in blender and I’m not a pro in programming, so please forgive if my problem is on a very basic level and my code looks dilettantish.

I’m trying to do something as simple as printing the location data of a moving camera at every frame within the framerange. I simplified the code to trace back the reason why this does not work and came up with this code:


import bpy

i = 0
while i <= 250:
    bpy.context.scene.frame_current = i
    print (bpy.context.scene.frame_current)
    print (bpy.context.scene.camera.location)

    i = i + 1

To my amazement this script indeed prints the frame_current correct (it starts with 0, increases by 1 in every line and ends with 250), but the location data of the camera stays allways the same - namely the location values which the camera had before the script was started. Now i wonder why blender prints the frame_current correctly while it fails to print the camera.location at the respective frame.

This seems to have something to do with the “while” statement, as I tryed the same thing with a script that just goes to the next frame and prints the data - and the data was printed correctly then.

Thanks for any helping advice in advance.
Cheers
j_mc

Hi blender needs to update when running scripts that simply change the value of frame_current.
Either use scene.frame_set(frame) or scene.update() to do this. Otherwise you just get the values of the current_frame of when the script was run.

I’m pretty sure scene.frame_set() calls scene.update() so both aren’t required.


import bpy


context = bpy.context
scene = context.scene
i = 0
while i <= 250:
    scene.frame_set(i)    
    print (scene.frame_current)
    print (scene.camera.location)


    i = i + 1

Also there are handlers that run on events. http://www.blender.org/documentation/blender_python_api_2_69_7/bpy.app.handlers.html?highlight=handlers#bpy.app.handlers.frame_change_post


import bpy


def my_handler(scene):
    print("Frame Change", scene.frame_current)
    print("Camera location:", scene.camera.location)


bpy.app.handlers.frame_change_pre.append(my_handler)

Hey batFINGER

thanks for your quick reply. Easy enough - works perfectly. I suspected it to be something like this…

Thanks again! Cheers
j_mc