6
$\begingroup$

Here is my setup:

  • I have the default cube
  • I make a sphere and move it y+4 (now at 0,4,0)
  • I parent the sphere (child) to the cube (parent)
  • the sphere location is [0,4,0] in local coordinates. It's the same for global coordinates. (This is a simplified example.)

I want to programmatically get the sphere's coordinates in the global space.

Scouring the web, I have found the following general formula for getting global coordinates from local ones:

sphere.matrix_world * sphere.location

In the above example, if I plug that into the python console, it produces [0,8,0]. Why 8? It should be 4, no? Is this not the correct formula? If I make the example more complex (by rotating the cube, for example) I still get this 'doubling' effect. [0,3,0] becomes [0,6,0]. What is the correct python expression to get the correct global coordinates of the parented sphere?

$\endgroup$

1 Answer 1

8
$\begingroup$

The formula is

default_cube.matrix_world * sphere.matrix_basis

You can directly get the global coordinates (including constraints) of the sphere from

sphere.matrix_world.translation

See Object.matrix_basis, mathutils.Matrix

$\endgroup$
3
  • 2
    $\begingroup$ There's also a more or less equal alternative to Object.matrix_world.translation: to_translation(). In contrast to translation, there's always a copy made and modifications to the Vector object won't affect the original matrix. $\endgroup$
    – CodeManX
    Commented Jan 7, 2015 at 9:04
  • $\begingroup$ i have a sphere (with follow path constraints) parented to empty. when i run print(sphere.matrix_world.translation) i don't get the correct world space coordinates. But when i remove the constraint then it is correct. you claimed it should work with constraints. Do you know what changed in blender 3.1? $\endgroup$
    – Harry McKenzie
    Commented Aug 2, 2022 at 2:57
  • $\begingroup$ ah i found the reason here in this answer and need to call bpy.context.view_layer.update() and then the value of print(sphere.matrix_world.translation) is correct. $\endgroup$
    – Harry McKenzie
    Commented Aug 2, 2022 at 3:26

You must log in to answer this question.

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