如何在Three.js中创建3D梯形?现有截棱锥实现方案遇阻
解决Three.js中梯形(四棱台)模型的实现问题
嘿,这个问题我之前做项目的时候也碰到过!你现在用THREE.CylinderGeometry加4个分段来做四棱台,确实会遇到上下底边长不好控制的问题——因为这个几何体的radiusAtTop和radiusAtBottom对应的是外接圆的半径,不是四边形的边长本身。下面给你两种实用的解决方法,看哪种更适合你的需求:
方法一:调整CylinderGeometry参数精准控制正四棱台边长
如果你要的是正四棱台(上下底都是正方形),可以通过计算外接圆半径来适配你需要的边长。
原理:正四边形的外接圆半径 = 边长 / √2(因为正四边形的对角线长度是边长×√2,半径是对角线的一半)。
修改你的代码如下:
// 定义你需要的上下底边长和高度 const topSideLength = 140; const bottomSideLength = 150; const height = 50; // 计算对应的外接圆半径 const topRadius = topSideLength / Math.sqrt(2); const bottomRadius = bottomSideLength / Math.sqrt(2); // 创建几何体 const dash_geometry = new THREE.CylinderGeometry(topRadius, bottomRadius, height, 4, 1); const dash_material = new THREE.MeshLambertMaterial(dash_settings.material); const dash_mesh = new THREE.Mesh(dash_geometry, dash_material);
这样生成的四棱台上下底边长就正好是你设定的140和150了,而且保持正四边形的对称性。
方法二:手动构建几何体实现任意梯形/矩形台
如果你的需求是非正四边形的梯形台(比如上下底是长方形,或者边长不对称),那CylinderGeometry就不太适用了,这时候可以手动构建顶点来实现:
// 1. 定义四棱台的8个顶点(中心在原点,方便对称) const vertices = [ // 上底四个顶点:假设上底是140×100的长方形 new THREE.Vector3(-70, -50, 0), new THREE.Vector3(70, -50, 0), new THREE.Vector3(70, 50, 0), new THREE.Vector3(-70, 50, 0), // 下底四个顶点:假设下底是150×120的长方形,高度50 new THREE.Vector3(-75, -60, 50), new THREE.Vector3(75, -60, 50), new THREE.Vector3(75, 60, 50), new THREE.Vector3(-75, 60, 50) ]; // 2. 创建BufferGeometry并设置顶点 const dash_geometry = new THREE.BufferGeometry().setFromPoints(vertices); // 3. 定义面的索引(注意顶点顺序要符合右手定则,否则面会无法正确显示) const indices = [ // 上底面 0, 1, 2, 0, 2, 3, // 下底面 4, 5, 6, 4, 6, 7, // 四个侧面 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7 ]; // 4. 设置索引并计算法线(让光影正常显示) dash_geometry.setIndex(indices); dash_geometry.computeVertexNormals(); // 5. 创建材质和网格 const dash_material = new THREE.MeshLambertMaterial(dash_settings.material); const dash_mesh = new THREE.Mesh(dash_geometry, dash_material);
这种方法的好处是完全自定义,不管是梯形还是不规则的台体都能实现,自由度很高。
另外提醒一下:如果用手动构建的几何体,记得调用computeVertexNormals(),不然MeshLambertMaterial的光影效果会异常。
内容的提问来源于stack exchange,提问作者mdr
相关产品推荐
相关产品推荐

