Python Animation - Can change camera location but not always pointing correctly This code will randomly place the camera around an object, and point at it, for each frame of an animation. The problem is that sometimes it doesn't seem to be pointing directly at the center.



import bpy
import math
import mathutils
import time

from random import randint

def eraseAllKeyframes(scene,passedOB = None):

    if passedOB != None:

        ad = passedOB.animation_data

        if ad != None:
            print ('ad=',ad)
            passedOB.animation_data_clear()

            #scene.update()


def look_at(obj_camera, point):
    loc_camera = obj_camera.matrix_world.to_translation()
    direction = point - loc_camera
    # point the cameras '-Z' and use its 'Y' as up
    rot_quat = direction.to_track_quat('-Z', 'Y')
    # assume we're using euler rotation
    obj_camera.rotation_euler = rot_quat.to_euler()




scene = bpy.data.scenes["Scene"]

passedOB =  bpy.context.scene.objects.active
eraseAllKeyframes(scene,passedOB = None)

cp = mathutils.Vector((0.0, 0.0, 0.0))
cam = bpy.data.objects['Camera']

scene.frame_start = 1
scene.frame_end = 10

for i in range(10):

  #bpy.context.scene.frame_current=i
  #bpy.ops.anim.keyframe_insert(type='Location')

  x, y, z = randint(4,10), randint(4,10), randint(8,10)
  cam.location = (x, y, z)
  bpy.data.objects['Camera'].keyframe_insert('location', frame=i)

  look_at(cam, cp)
  bpy.data.objects['Camera'].keyframe_insert('rotation_euler', frame=i)

  #bpy.ops.object.paths_calculate()
  #bpy.context.scene.update()




scene.render.filepath = "E:\\testing"
scene.render.image_settings.file_format = "JPEG"
bpy.ops.render.render(animation=True)
So.. I don't know why, but the solution that worked for me was to split the keyframe assignment into two separate loops.

Investigations made it appear as though the 'camera look' function just wasn't being called.. "in time?" I'm not sure. Working code below.

for i in range(10):
  bpy.context.scene.frame_set(i)

  x, y, z = randint(6,15), randint(-6,16), randint(6,35)
  cam.location = (x, y, z)
  cam.keyframe_insert('location')


for i in range(10):
  bpy.context.scene.frame_set(i)

  look_at(cam, cp)
  cam.keyframe_insert('rotation_euler')