Three.js Child Mesh position always return (0,0,0)

自作多情 提交于 2019-12-18 05:14:16

问题


I loaded some objects via OBJLoader , loaded object contain one parent and multiple childs; then I apply Raycaster and find clicked child.

Then I want to update position of child object, but initial position comes zero for all childs.

var intersect = intersects[0].object;
intersect.position.y = intersect.position.y + 5; // 0 + 5 

But in my scene all looks fine. Also, If i remove clicked object, actually it is removed from scene. I think I missed some point their positions cant be (0,0,0). How can I reach their relative position ?


回答1:


Try this, then read position(). I had the same issue, got an answer here. (geom is your Meshes geometry.)

objMesh.centroid = new THREE.Vector3();
for (var i = 0, l = geom.vertices.length; i < l; i++) {
    objMesh.centroid.add(geom.vertices[i].clone());
}
objMesh.centroid.divideScalar(geom.vertices.length);
var offset = objMesh.centroid.clone();

objMesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x, -offset.y, -offset.z));

objMesh.position.copy(objMesh.centroid);



回答2:


The position is relative to the parent

Multiply the position by the transform of the parent to get the world-space coordinates, if that's what you're seeking




回答3:


Here is code for set Transform Control into center of object:

let objLoader = new THREE.OBJLoader();
    let mtlLoader = new THREE.MTLLoader();
    mtlLoader.load("path/to/mtlFile.mtl", (materials) => {
        materials.preload();
        objLoader.setMaterials(materials).load("path/to/objFile.obj", (object3d) => {
            object3d.traverse((child) => {
                if (child instanceof THREE.Mesh) {
                    child.geometry.computeBoundingBox();
                    let matrix = new THREE.Vector3();
                    let offset = child.geometry.boundingBox.getCenter(matrix);
                    child.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x, -offset.y, -offset.z));
                    child.position.copy(offset);
                    objects.push(child);
                }
            });
            scene.add(object3d);
        });
    });



回答4:


That is because all objects in a obj file have their pivot at World 0,0,0 no matter where their local pivot was before exporting.



来源:https://stackoverflow.com/questions/14493019/three-js-child-mesh-position-always-return-0-0-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!