Get size of Object3D in Three.js

2020-08-26 00:17发布

问题:

I have this 3D object in my scene:

var icon = new THREE.Object3D()

var iconTexture = THREE.ImageUtils.loadTexture('images/icon.png'),
      iconMaterial = new THREE.SpriteMaterial({
      map: iconTexture,
      color: 0xffffff,
      opacity: 1
});

var iconSprite = new THREE.Sprite(iconMaterial);

iconSprite.scale.set(14, 14, 1.0);
iconSprite.position.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.75);

icon.position.setLength(0);

icon.add(iconSprite);

icon.position.y = 15;
icon.position.z = 20;
scene.add(icon);
scene.updateMatrixWorld(true);

I manged to get the position of this object:

var position = new THREE.Vector3();
position.getPositionFromMatrix( icon.matrixWorld );
console.log(position.x + ',' + position.y + ',' + position.z);

But I can't get the size of that object. I tried something like that:

console.log("sizes: "+icon.min+", "+icon.max);

But got this output: sizes: undefined, undefined.

Is there any way to get the size of that object?

回答1:

THREE.Sprite() has a geometry property so you can do:

if( iconSprite.geometry.boundingBox === undefined )
    iconSprite.geometry.computeBoundingBox ();

and you can get all the info you need from the .boundingBox property from its own properties .boundingBox.min and .boundingBox.max.



回答2:

You could possibly create bounding box from your object:

var bbox = new THREE.Box3().setFromObject(icon);

If you have bounding box you can get it's min and max.

Max.z - Min.z -> height

Max.x - Min.x -> width

Max.y - Min.y -> depth