12
$\begingroup$

This script changes the active object's location, it could also change the rotation or scale, it also prints the object's world matrix before and after changing the location.

import bpy
obj = bpy.context.object
print(obj.matrix_world)
obj.location = 1, 2, 3
print(obj.matrix_world)

The output shows the same matrix as before and after the translation:

<Matrix 4x4 (1.0000, 0.0000, 0.0000, 0.0000)
            (0.0000, 1.0000, 0.0000, 0.0000)
            (0.0000, 0.0000, 1.0000, 0.0000)
            (0.0000, 0.0000, 0.0000, 1.0000)>
<Matrix 4x4 (1.0000, 0.0000, 0.0000, 0.0000)
            (0.0000, 1.0000, 0.0000, 0.0000)
            (0.0000, 0.0000, 1.0000, 0.0000)
            (0.0000, 0.0000, 0.0000, 1.0000)>

However accessing the matrix from the python console, bpy.context.object.matrix_world, shows the correct world matrix with the translation (the last column):

Matrix(((1.0, 0.0, 0.0, 1.0),
        (0.0, 1.0, 0.0, 2.0),
        (0.0, 0.0, 1.0, 3.0),
        (0.0, 0.0, 0.0, 1.0)))

Therefore, what is the correct way to access the modified matrix values after changing an object's location, rotation, or scale?

$\endgroup$

2 Answers 2

16
$\begingroup$

Note for those using blender 2.8x: scene.update() has been removed as of 2.80. Use bpy.context.view_layer.update() instead, as per this post.

$\endgroup$
1
  • 1
    $\begingroup$ If in your script the object is moving between frames, you can simply use: scene.frame_set(scene.frame_current) this will update the matrix_world of the objects $\endgroup$ Commented Dec 2, 2020 at 9:03
7
$\begingroup$

Stackoverflow has a similar question and answer on the same issue. The problem is blender is not recalculate the matrix immediately after modifying the transformation.

As mgibsonbr notes, to have the correct values, add scene.update() after the changes to recalculate the matrix.

import bpy
obj = bpy.context.object
print(obj.matrix_world)
obj.location = 1, 2, 3
bpy.context.scene.update()
print(obj.matrix_world)

Which now correctly prints:

<Matrix 4x4 (1.0000, 0.0000, 0.0000, 0.0000)
            (0.0000, 1.0000, 0.0000, 0.0000)
            (0.0000, 0.0000, 1.0000, 0.0000)
            (0.0000, 0.0000, 0.0000, 1.0000)>
<Matrix 4x4 (1.0000, 0.0000, 0.0000, 1.0000)
            (0.0000, 1.0000, 0.0000, 2.0000)
            (0.0000, 0.0000, 1.0000, 3.0000)
            (0.0000, 0.0000, 0.0000, 1.0000)>
$\endgroup$
1
  • $\begingroup$ what is the equivalent of bpy.context.scene.update() in blender 3.1? EDIT ahhh found it bpy.context.view_layer.update() $\endgroup$
    – Harry McKenzie
    Commented Aug 2, 2022 at 3:05

You must log in to answer this question.

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