javascript - How to write a getworldposition function in Three.js? - Stack Overflow

admin2025-04-19  1

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?
}

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?
}
Share Improve this question asked Jan 24, 2015 at 2:53 user4485105user4485105
Add a ment  | 

2 Answers 2

Reset to default 4

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/docs/#api/core/Object3D

Try checking out how Jerome Etienne did his ObjCoord library to get an idea:

https://github./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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745001758a279270.html

最新回复(0)