如何获取three.js中加载的.obj的绝对位置?

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

正在加载 .obj:

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

我尝试用 mrdoobs 代码找到位置:

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);

但是这失败了

objMesh.geometry is undefined

这对加载的网格物体来说是不可能的吗?

有可能,但在您的情况下,objMesh 似乎是 function ( objMesh ) {...} 范围内的局部变量。

所以你可以声明一个全局变量,比方说mesh,然后在onLoad回调函数

中设置它的值
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()
            }

        } );

然后将 mrdoob 的代码应用于 mesh 变量,而不是 objMesh

或者,您可以将 mrdoob 的代码包装在一个函数中,然后在回调 onLoad 函数中使用您的网格参数调用此函数:

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);
}

在回调函数中调用

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

        } );