0

Is there a simple way in python to rotate/position a camera so that a specific point (X,Y,Z) is in the middle of the camera viewfinder in Blender 2.8?

Leander
  • 26,725
  • 2
  • 44
  • 105
vndep
  • 713
  • 1
  • 9
  • 29

1 Answers1

2
  1. Get the camera-object direction as a vector by subtracting the cameras location from the objects location: direction
  2. Convert this vector to a look at quaternion with the vectors to_track_quat('Z', 'Y') function. This function returns a quaternion rot which points its Z in the direction of the direction vector and its Y in the direction of the global Y.
    Convert rot to a 4x4 matrix.
  3. Convert the cameras location into a Translation Matrix and store it in loc.
  4. Compose the new camera matrix by matrix-multiplying the loc matrix and the rot matrix and assign it to the camera matrix_world.
import bpy
import mathutils

cam = bpy.context.scene.camera
object = bpy.context.active_object

direction = cam.location - object.location

rot = direction.to_track_quat('Z', 'Y').to_matrix().to_4x4()
loc = mathutils.Matrix.Translation(cam.location)

cam.matrix_world =  loc @ rot
Leander
  • 26,725
  • 2
  • 44
  • 105
  • thanks for the explanation. Would you be able to comment on this post: https://blender.stackexchange.com/questions/151034/blender-2-8-python-manipulating-the-camera-for-resized-objects – vndep Sep 08 '19 at 15:03