问题
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