I'm trying to implement a prototype for a custom render engine using blender as content creation tool. One remaining questions is: How can we calculate the direction and up vector of the camera by its actual position and rotation properly?
3 Answers
$\begingroup$
$\endgroup$
2
2.8x
import bpy
from mathutils import Vector
cam = bpy.data.objects['Camera']
up = cam.matrix_world.to_quaternion() @ Vector((0.0, 1.0, 0.0))
cam_direction = cam.matrix_world.to_quaternion() @ Vector((0.0, 0.0, -1.0))
2.7x
import bpy
from mathutils import Vector
cam = bpy.data.objects['Camera']
up = cam.matrix_world.to_quaternion() * Vector((0.0, 1.0, 0.0))
cam_direction = cam.matrix_world.to_quaternion() * Vector((0.0, 0.0, -1.0))
-
$\begingroup$ Nice. Thank you pink vertex! I've also added a cam_direction.normalize() and up.normalize(). Works like a charm. $\endgroup$– p2orCommented Jul 3, 2014 at 18:47
-
$\begingroup$ Since it uses
.to_quaternion
, callingnormalize
should be unnecessary because a pure rotation preserves the length of a vector, which equals 1.0 in both of these cases. $\endgroup$ Commented Jul 4, 2014 at 15:32
$\begingroup$
$\endgroup$
1
Alternatively
Can get the global directions of local axes from the columns of the matrix world's rotation matrix.
>>> cam = C.scene.camera
>>> cam
bpy.data.objects['Camera']
>>> right, up, back = cam.matrix_world.to_3x3().transposed()
>>> cam_direction = -back
$\begingroup$
$\endgroup$
1
As of Blender 2.8x, you have to use the @
operator to multiply matrices:
up = cam.matrix_world.to_quaternion() @ Vector((0.0, 1.0, 0.0))
cam_direction = cam.matrix_world.to_quaternion() @ Vector((0.0, 0.0, -1.0))
Release Notes: https://wiki.blender.org/wiki/Reference/Release_Notes/2.80/Python_API#Matrix_Multiplication
Matrix multiplication previously used *, scripts should now use @ for multiplication (per PEP 465).
-
2$\begingroup$ Not sure if it's worth finding and answering all pre @ change answers. Added this q / a to be a "catchall" for searching on error message. blender.stackexchange.com/questions/129473/… $\endgroup$ Commented Dec 12, 2019 at 13:29