如何在 Three.js 中获取立方体的高度

How do I get the height of a cube in Three.js

我有以下代码;

// World
var geometry = new THREE.BoxGeometry( 100, 200, 100 );
var material = new THREE.MeshLambertMaterial( { color: 'green' } );
var cube = new THREE.Mesh( geometry, material );
cube.position.y = (cube.height / 2); // this doesn't work
scene.add( cube );

获取立方体高度的正确方法是什么?我知道高度 = 100,但我想了解如何使用程序代码获取高度。

您创建的长方体几何对象具有 3 个属性(高度、宽度和深度)。这 3 个属性被读作 x、y、z。结果,如果你想改变高度,你将不得不改变Y轴。

geometry.scale.y = 200;

你得从几何上算出来。

//you need to get correct verts 0 and 4 are for example
var height=cube.geometry.vertices[4].y-cube.geometry.vertices[0].y;

对象的边界框将给出其准确尺寸:

var cube_bbox = new THREE.Box3();
cube_bbox.setFromObject( cube );

现在你有了向量 cube_bbox.maxcube_bbox.min 所以:

cube_height = cube_bbox.max.y - cube_bbox.min.y;

如果您使用 THREE.BoxGeometry 创建立方体网格,您可以通过访问几何体的 parameters 属性 来获取立方体的高度:

height = mesh.geometry.parameters.height;

如果您更改了网格 属性 scale.y 的默认值 1,那么您必须将上述数量乘以 scale.y

three.js r.71