3
$\begingroup$

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?

$\endgroup$
8
$\begingroup$

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))

cam coordinates

| improve this answer | |
$\endgroup$
  • $\begingroup$ Nice. Thank you pink vertex! I've also added a cam_direction.normalize() and up.normalize(). Works like a charm. $\endgroup$ – p2or Jul 3 '14 at 18:47
  • $\begingroup$ Since it uses .to_quaternion, calling normalize should be unnecessary because a pure rotation preserves the length of a vector, which equals 1.0 in both of these cases. $\endgroup$ – pink vertex Jul 4 '14 at 15:32
3
$\begingroup$

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
| improve this answer | |
$\endgroup$
  • $\begingroup$ Yeah, good idea. $\endgroup$ – p2or Dec 14 '19 at 12:29
1
$\begingroup$

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).

| improve this answer | |
$\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.