You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并不同Three.js几何体的两个顶点?含代码及平移需求

实现两个立方体指定顶点合并到中点的Three.js方案

嘿,我来帮你搞定这个顶点合并的需求!下面是一步步的实现思路和代码示例,完全贴合你的场景:

核心步骤说明

要完成这个操作,关键是把局部顶点坐标转换为世界坐标计算中点,再把顶点平移到中点位置,具体分为这几步:

  • 第一步:获取两个立方体上指定顶点的局部坐标,转换为世界坐标
  • 第二步:计算这两个世界坐标的中点
  • 第三步:将两个顶点分别平移到中点位置(注意要转换回局部坐标处理)
  • 第四步:更新几何体数据,让Three.js生效渲染

完整代码示例

假设我们要合并第一个立方体的第0号顶点,和第二个立方体的第5号顶点(你可以根据需求替换顶点索引):

// 假设你已经有了cubeMesh1、cubeMesh2和scene实例
// 1. 定义要合并的目标顶点索引
const vertexIndex1 = 0; // cubeMesh1上的目标顶点
const vertexIndex2 = 5; // cubeMesh2上的目标顶点

// 2. 获取顶点的局部坐标,并转换为世界坐标
const positionAttr1 = cubeMesh1.geometry.attributes.position;
const positionAttr2 = cubeMesh2.geometry.attributes.position;

// 创建临时向量存储坐标
const v1Local = new THREE.Vector3(
  positionAttr1.getX(vertexIndex1),
  positionAttr1.getY(vertexIndex1),
  positionAttr1.getZ(vertexIndex1)
);
const v2Local = new THREE.Vector3(
  positionAttr2.getX(vertexIndex2),
  positionAttr2.getY(vertexIndex2),
  positionAttr2.getZ(vertexIndex2)
);

// 转换为世界坐标(考虑网格的位移、旋转、缩放)
const v1World = v1Local.clone();
const v2World = v2Local.clone();
cubeMesh1.localToWorld(v1World);
cubeMesh2.localToWorld(v2World);

// 3. 计算世界坐标的中点
const midPointWorld = new THREE.Vector3();
midPointWorld.lerpVectors(v1World, v2World, 0.5); // 线性插值得到中点

// 4. 将中点转换为每个网格的局部坐标,更新顶点位置
// 处理cubeMesh1的顶点
const midPointLocal1 = midPointWorld.clone();
cubeMesh1.worldToLocal(midPointLocal1);
positionAttr1.setXYZ(vertexIndex1, midPointLocal1.x, midPointLocal1.y, midPointLocal1.z);

// 处理cubeMesh2的顶点
const midPointLocal2 = midPointWorld.clone();
cubeMesh2.worldToLocal(midPointLocal2);
positionAttr2.setXYZ(vertexIndex2, midPointLocal2.x, midPointLocal2.y, midPointLocal2.z);

// 5. 标记几何体需要更新,让Three.js重新渲染
positionAttr1.needsUpdate = true;
positionAttr2.needsUpdate = true;

关键注意事项

  • 顶点索引确认:Three.js的BoxGeometry顶点顺序是固定的,你可以通过打印positionAttr1.array来查看顶点的具体坐标,避免选错目标顶点
  • 变换矩阵影响:必须使用localToWorld和worldToLocal处理坐标,因为网格可能设置了位移、旋转或缩放,直接用局部坐标计算会出错
  • 更新标记:修改顶点后一定要设置needsUpdate = true,否则Three.js不会读取新的顶点数据进行渲染

内容的提问来源于stack exchange,提问作者Hakim Shaan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:52:26