Might be very basic question. I’ve just started learning. I added a cube in my threejs scene. I moved its origin of its geometry by using applyMatrix , as:
cubeGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 2, 0.5, 2 ) );
then of course added the cube in my scene.
The cube looks in the scene as translated to that place, which is good. But when I console.log
either the cube’s position or its .getWorldPosition()
, it gives me a (0, 0, 0) whatever I try. I tried updating world matrix, using scene.updateMatrixWorld()
before calling .getWorldPosition()
but to no avail.
Could someone help out please?
Translating the origin of a geometry has no effect on the transformation of an instance of Object3D
(in your case a Mesh
). You just alter the geometry’s vertices and normal data.
If you translate a 3D object by altering its position, rotation or scale property instead, then you effectively change its Object3D.matrix
and Object3D.matrixWorld
representing the transformation in local and world space. Object3D.matrixWorld
is later used in the vertex shader in order to transform the vertices of your geometry into their final position for rendering. It’s also used inside Object3D.getWorldPosition()
.
What would be the best way to get the world coordinates for a mesh which may be nested in multiple Object3D
s?
The intended API method for this use case is Object3D.getWorldPosition().
So would I have to recursively do it for all parent 'Object3D`s of the mesh?
Each parent could have its local position changed.
WorldPosition is irrespective of nesting. If you want worldPos for an object nested deep within, you don’t need recursion. Just use .getWorldPosition()
on the nested object.
Perfect, the trick was to updateMatrixWorld()
after changing the position of the object. That’s why I was getting ( 0, 0, 0 ) for all object while logging them in console. makeTranslation( x, y, z )
is not useful for changing the pos, as rightly pointed out.