Three.js: Keeping child below parent mesh

自闭症网瘾萝莉.ら 提交于 2019-12-31 05:04:15

问题


I'm trying to create a table in Three.js but the legs of the table goes through the parent.

Parent Mesh:

    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 (The legs of the table)

   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)

The relation between the two

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

How do i make the legs of the table always stay below the table?


回答1:


THREE.BoxGeometry creates a symmetric box with a width, height and depth, where the center of the box is at (0, 0, 0).

If the plate of the table should be on top of the legs, then you've to change the y position of the plate, by the half height of the leg and the half height of the plate (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);

If you want that the bottom of the legs is at 0.0, then you've to "lift up" the legs by 0.5 and the palte by 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)
// ...


来源:https://stackoverflow.com/questions/57789080/three-js-keeping-child-below-parent-mesh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!