代码之家  ›  专栏  ›  技术社区  ›  user3471528

Threej位置网格到0,0,0

  •  1
  • user3471528  · 技术社区  · 3 年前

    我试图将一个简单的立方体定位在0,0,0。

    当我在0,0,0中定位一个框时,我会得到以下结果: enter image description here

    但这是不对的。这就是我需要实现的目标: enter image description here

    我的代码非常简单:

    const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));
    cube.position.x = 0;
    cube.position.z = 0;
    cube.position.y = 0;
    cube.material = new THREE.MeshPhongMaterial({ color: 'green' });
    this.scene.add(cube);
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Rabbid76    3 年前

    网格的中心是(0,0,0),因为 BoxGeometry 创建最小值为的网格 (-宽/2,-高/2,-深/2) 和最大值 (宽/2,高/2,深/2) 。您的多维数据集的大小为 (1,1,1) 。所以立方体的最小值是 (-0.5、-0.5和-0.5) 并且必须将立方体移动(0.5,0.5,0.5):

    const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));
    cube.position.set(0.5, 0.5, 0.5)
    

    您也可以不更改网格的位置 translate 几何图形:

    const cubeGeometry = new THREE.BoxGeometry(1, 1, 1).translate(0.5, 0.5, 0.5);
    const cube = new THREE.Mesh(cubeGeometry);
    

    更通用的方法是通过网格边界框的最小值平移网格:

    const geometry = new THREE.BoxGeometry(1, 1, 1);
    
    // this works for any geometry
    geometry.computeBoundingBox();
    geometry.translate(
        -geometry.boundingBox.min.x,
        -geometry.boundingBox.min.y,
        -geometry.boundingBox.min.z);