52

How do I get the global position of an Object3D inside another Object3D?

setup:

var parent = new THREE.Object3D();
parent.position.set(100, 100, 100);

var child = new THREE.Object3D();
child.position.set(100, 100, 100);
parent.add(child);

scene.add(parent);

notes:

I thought that this would be the way to do it:

console.log(child.localToWorld(parent.position));

...but it gives me (100, 100, 100), not (200, 200, 200).

XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
TunnelVision
  • 523
  • 1
  • 4
  • 5

2 Answers2

69

You can extract the world position like so:

var target = new THREE.Vector3(); // create once an reuse it

child.getWorldPosition( target );

target will contain the result.

EDIT: updated to three.js r.120

WestLangley
  • 102,557
  • 10
  • 276
  • 276
  • Thank you WestLangley, following your advice I did this: **console.log(parent.position.getPositionFromMatrix( child.matrixWorld ))** But, since the live code is actruly inside a loop that moves things around, this resulted in some weird artifacts, where the velocity of the parent object would increase dramaticly (this only console.logging the childs position) ! Since I don't understand exactly what's going on (will read up on it tho), I ended up doing: **console.log(parent.position.clone().getPositionFromMatrix( child.matrixWorld ))** *Thanks again.* – TunnelVision Feb 26 '13 at 23:30
  • 1
    No, no! Create a separate vector outside the render loop, and assign it the position value inside the render loop. – WestLangley Feb 27 '13 at 00:36
  • 1
    Thank you for: scene.updateMatrixWorld(). Always my vector was (0,0,0), because the scene didn't update the matrix. I used the update method and now works fine! :) Also, getPositionFromMatrix is now setFromMatrixPosition (three.js r65) – Alin Ciocan Feb 06 '14 at 12:36
  • Perfect, that's just what I was missing and looking for. thanks a lot! – Pic Mickael Oct 26 '15 at 13:44
  • Ah, awesome for children objects I need to update the parent matrixWorld. Perfect. Thank you. – Hobbes Jan 08 '17 at 19:07
  • Following this, I still get 0, 0, 0... Is there anything I might have missed? – James Heald May 02 '17 at 19:14
  • @WestLangley You said "In practice, however, the renderer calls updateMatrixWorld() for you in each render loop, so you don't have to.", but this means that when accessing the `object.matrixWorld` before `renderer.render`, then we're accessing the last frame's matrix, not this frame's matrix? – trusktr Sep 29 '17 at 06:36
13

In threejs r89 you can just get the world position by Object3D.getWorldPosition. I don't know when it was added.

zwcloud
  • 4,546
  • 3
  • 40
  • 69
  • 1
    This works, but as per the other answer make sure to call `parent.updateMatrixWorld()` or `scene.updateMatrixWorld` beforehand. – ty. Feb 10 '19 at 19:00