Reputation:
How to write a getworldposition function in Three.js that returns a vector?
That's my code to get the World Position of obj stored in vector vec.
obj.updateMatrixWorld();
var vec= new THREE.Vector3();
vec.setFromMatrixPosition(obj.matrixWorld);
Now I want use this three lines as a function to use it like:
var vector = getWorldPosition(obj);
Is this the right way to do it?
function getWorldPosition(obj)
{
obj.updateMatrixWorld();
var vec= new THREE.Vector3();
vec.setFromMatrixPosition(obj.matrixWorld);
return {vec.x, vec.y, vec.z}; // Like this?
}
Upvotes: 4
Views: 4876
Reputation: 189
now you can use Object3D().getWorldPosition ( target ) to get the world position
target — the result will be copied into this Vector3. Returns a vector representing the position of the object in world space.
example:
const anyMesh = new THREE.Mesh(g,m)
let handVec = new THREE.Vector3()
anyMesh.getWorldPosition(handVec)
so the handVec is world position of anyMesh
more detail you can check the doc: https://threejs.org/docs/#api/core/Object3D
Upvotes: 4
Reputation: 666
Try checking out how Jerome Etienne did his ObjCoord library to get an idea:
https://github.com/jeromeetienne/threex.objcoord
It's a bit outdated however:
/**
* get the world position
* @return {THREE.Vector3} the world position
*/
THREEx.ObjCoord.worldPosition = function(object3d){
object3d.updateMatrixWorld();
var worldMatrix = object3d.matrixWorld;
var worldPos = new THREE.Vector3().getPositionFromMatrix(worldMatrix);
return worldPos;
}
Your method of using the vector directly is the correct way with the latest THREE version.
Upvotes: 1