问题
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