Converting global coordinates of object B
to local coordinates of object A
The global coordinate of object A (obj_a
)
global_coord = obj_a.matrix_world.translation
To convert from a global coordinate to the local space of object A
local_coord = obj_a.matrix_world.inverted() * global_coord
Using the global coordinate of object A in the local coordinate equation above yeilds Matrix.Identity().translation
, since multiplying a matrix by its inverse results in the identity matrix, which has a translation component of (0, 9, 0)
aka the origin of our local coordinate system.
Putting it altogether in a test script. Object A is represented by the context object All #other selected objects are iterated as object B.
import bpy
# context for test code
from bpy import context
selected_obs = context.selected_objects
ob_a = context.object
#selected_obs.remove(ob_a) # will be at local origin
mwi = ob_a.matrix_world.inverted()
print("local coordinates of", ob_a.name)
for ob_b in selected_obs:
local_pos = mwi * ob_b.matrix_world.translation
print(ob_b.name, local_pos)
Result of running on Default Scene, with cube then camera as active object
local coordinates of Cube
Cube <Vector (0.0000, 0.0000, 0.0000)>
Lamp <Vector (4.0762, 1.0055, 5.9039)>
Camera <Vector (7.4811, -6.5076, 5.3437)>
local coordinates of Camera
Cube <Vector (-0.3382, -0.3767, -11.2523)>
Lamp <Vector (3.1254, 3.9298, -6.5683)>
Camera <Vector (0.0000, 0.0000, -0.0000)>
Global locs from console
>>> for o in C.scene.objects:
... o.name, o.matrix_world.translation
...
('Cube', Vector((0.0, 0.0, 0.0)))
('Lamp', Vector((4.076245307922363, 1.0054539442062378, 5.903861999511719)))
('Camera', Vector((7.481131553649902, -6.5076398849487305, 5.34366512298584)))
>>>
.inverted()
with a period, it works when I try it. Isobject
not at the origin ? $\endgroup$