Three.js:让孩子在父网格下

时间:2019-09-04 13:06:00

标签: javascript reactjs animation three.js 3d

我正在尝试在Three.js中创建一个表,但是表的两边通过父级。 Current Result

父网格:

    const boxWidth = 2; const boxHeight = 0.1; const boxDepth = 1;
    const tableBoardGeometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
    const textureLoader = new THREE.TextureLoader();
    const customPicture = textureLoader.load('https://threejsfundamentals.org/threejs/lessons/resources/images/compressed-but-large-wood-texture.jpg')
    const tableBoardMaterial = new THREE.MeshLambertMaterial({map: customPicture})
    const tableBoard = new THREE.Mesh(tableBoardGeometry, tableBoardMaterial)
    tableBoard.position.set(0, 0, 0)

SubMesh(桌子的腿)

   const tableLegsGeometry = new THREE.BoxGeometry(0.05, 1, 0.05);
   const tableLegsMaterial = new THREE.MeshLambertMaterial(({map: customPicture}))
   const tableLeg1 = new THREE.Mesh(tableLegsGeometry, tableLegsMaterial)
   const tableLeg2 = new THREE.Mesh(tableLegsGeometry, tableLegsMaterial)
   const tableLeg3 = new THREE.Mesh(tableLegsGeometry, tableLegsMaterial)
   const tableLeg4 = new THREE.Mesh(tableLegsGeometry, tableLegsMaterial)
   tableLeg1.position.set(0.9, 0, -0.4)
   tableLeg2.position.set(-0.9, 0, -0.4)
   tableLeg3.position.set(-0.9, 0, 0.4)
   tableLeg4.position.set(0.9, 0, 0.4)

两者之间的关系

    const group = new THREE.Group();
    tableBoard.add(tableLeg1, tableLeg2, tableLeg3, tableLeg4);
    scene.add(tableBoard);

如何使桌腿始终保持在桌下方?

1 个答案:

答案 0 :(得分:1)

THREE.BoxGeometry创建一个具有宽度,高度和深度的对称框,框的中心位于(0,0,0)。

如果桌子的盘子应该放在腿的顶部,则必须通过腿的一半高度和盘子的一半高度来改变盘子的y位置(1.0 / 2 + 0.1 / 2 = 0.55):

const boxWidth = 2; const boxHeight = 0.1; const boxDepth = 1;
const tableBoardGeometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
// ...
const tableBoard = new THREE.Mesh(tableBoardGeometry, tableBoardMaterial);
tableBoard.position.set(0, 0.55, 0);

如果您希望腿的底部为0.0,则必须将腿“抬高” 0.5,将调色板“抬高” 1.05:

const tableBoard = new THREE.Mesh(tableBoardGeometry, tableBoardMaterial)
tableBoard.position.set(0, 1.05, 0)
const tableLegsGeometry = new THREE.BoxGeometry(0.05, 1, 0.05);
const tableLeg1 = new THREE.Mesh(tableLegsGeometry, tableLegsMaterial)
// ...
tableLeg1.position.set(0.9, 0.5, -0.4)
// ...