5
$\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$

3 Answers 3

10
$\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

$\endgroup$
2
  • $\begingroup$ Nice. Thank you pink vertex! I've also added a cam_direction.normalize() and up.normalize(). Works like a charm. $\endgroup$
    – p2or
    Commented Jul 3, 2014 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$ Commented Jul 4, 2014 at 15:32
6
$\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
$\endgroup$
1
  • $\begingroup$ Yeah, good idea. $\endgroup$
    – p2or
    Commented Dec 14, 2019 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).

$\endgroup$
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .