how to get the absolute position of loaded .obj in three.js?

天大地大妈咪最大 提交于 2020-01-04 06:26:06

问题


loading the .obj:

        loader.load( 'test.obj', function ( objMesh ) {
                objMesh.traverse( function ( child ) {
                if ( child instanceof THREE.Mesh ) {
                       child.material = mat2;
                }
            } );

I tried to find the position with mrdoobs code:

objMesh.geometry.computeBoundingBox();

var boundingBox = objMesh.geometry.boundingBox;

var position = new THREE.Vector3();
position.subVectors( boundingBox.max, boundingBox.min );
position.multiplyScalar( 0.5 );
position.add( boundingBox.min );

position.applyMatrix4( objMesh.matrixWorld );

alert(position.x + ',' + position.y + ',' + position.z);

however this fails with

objMesh.geometry is undefined

Is this not possible with loaded meshes?


回答1:


It's possible, but in your case seems that the objMesh is a local variable in the scope of function ( objMesh ) {...}.

So you can declare a global variable, let's say mesh and then set its value inside the onLoad callback function

var mesh;
...
loader.load( 'test.obj', function ( objMesh ) {
            objMesh.traverse( function ( child ) {
            if ( child instanceof THREE.Mesh ) {
                   child.material = mat2;
                   mesh = child; // set value to the global variable, applicable, if the objMesh has one child of THREE.Mesh()
            }

        } );

and then apply mrdoob's code to the mesh variable, not the objMesh.

Or, you can wrap mrdoob's code in a function and then call this function in the callback onLoad function with a parameter of your mesh:

function absPos( myMesh ){
    myMesh.geometry.computeBoundingBox();

    var boundingBox = myMesh.geometry.boundingBox;

    var position = new THREE.Vector3();
    position.subVectors( boundingBox.max, boundingBox.min );
    position.multiplyScalar( 0.5 );
    position.add( boundingBox.min );

    position.applyMatrix4( myMesh.matrixWorld );

    alert(position.x + ',' + position.y + ',' + position.z);
}

calling it in the callback function

loader.load( 'test.obj', function ( objMesh ) {
            objMesh.traverse( function ( child ) {
            if ( child instanceof THREE.Mesh ) {
                   child.material = mat2;
                   absPos( child ); // call our function
            }

        } );


来源:https://stackoverflow.com/questions/40863672/how-to-get-the-absolute-position-of-loaded-obj-in-three-js

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