如何在three.js中获取加载的.obj的绝对位置? [英] how to get the absolute position of loaded .obj in three.js?

查看:93
本文介绍了如何在three.js中获取加载的.obj的绝对位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加载 .obj:

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

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

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

然而这失败了

objMesh.geometry is undefined

这对于加载的网格是不可能的吗?

Is this not possible with loaded meshes?

推荐答案

这是可能的,但在你的情况下似乎 objMeshfunction ( objMesh ) 范围内的局部变量{...}.

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

所以你可以声明一个全局变量,比如说mesh,然后在onLoad回调函数中设置它的值

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

        } );

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

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

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

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

在回调函数中调用

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

        } );

这篇关于如何在three.js中获取加载的.obj的绝对位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆