Three.JS: Get position of rotated object

2019-06-13 20:22发布

In Three.JS, I am capable of rotating an object about its origin. If I were to do this with a line, for instance, the line rotates, but the positions of its vertices are not updated with their new locations. Is there some way to apply the rotation matrix to the position of the vertices to find the new position of the point? Say I rotate a line with points at (0,0,0) and (0,100,100) by 45° on the x, 20° on the y, and 100° on the z. How would I go about finding the actual position of the vertices with respect to the entire scene.

Thanks

1条回答
甜甜的少女心
2楼-- · 2019-06-13 20:59

yes, 'entire scene' means world position.

THREE.Vector3() has a applyMatrix4() method,

you can do the same things that the shader does so in order to project a vertex into world space you would do this

yourPoint.applyMatrix4(yourObject.matrixWorld);

to project that into camera space you can apply this next

yourPoint.applyMatrix4(camera.matrixWorld);

to get an actual screen position in -1 to 1

yourPoint.applyMatrix4(camera.projectionMatrix);

you would access your point like this

var yourPoint = yourObject.geometry.vertices[0]; //first vertex

also, rather than doing this three times, you can just combine the matrices. Didnt test this, but something along the lines of this. Might go the other way:

var neededPVMmatrix = new THREE.Matrix4().multiplyMatrices(yourObject.matrixWorld, camera.matrixWorld);
neededPVMmatrix.multiplyMatrices(neededPVMmatrix, camera.projectionMatrix);

if you need a good tutorial on what this does under the hood i recommend this

Alteredq posted everything there is to know about three.js matrices here

edit

One thing to note though, if you want just the rotation, not the translation, you need to use the upper 3x3 portion which is the rotation matrix, of the models world matrix. This might be slightly more complicated. I forgot what three.js gives you, but i think the normalMatrix would do the trick, or perhaps you can convert your THREE.Vector3() to THREE.Vector4(), and set .w to 0, this will prevent any translation from being applied.

edit2

if you want to move the line point in your example, instead of applying it to the particle, apply it to

var yourVertexWorldPosition = new THREE.Vector3().clone(geo.vertices[1]); //this is your second line point, to whatever you set it in your init function
yourVertexWorldPosition.applyMatrix4();//this transforms the new vector into world space based on the matrix you provide (line.matrixWorld)
查看更多
登录 后发表回答