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

ThreeJS切换地形时移除旧平面?按钮点击地形堆叠问题

解决方案:保留当前地形引用,生成前移除旧实例

问题根源在于你没有保存当前已生成地形的引用,调用scene.remove()时找不到对应的对象,导致旧地形残留。按以下步骤修改即可解决:

1. 声明全局变量存储当前地形

在脚本顶部定义一个变量,用来跟踪当前显示的地形对象:

let currentGround = null; // 存储当前地形的全局引用

2. 修改地形生成函数,添加移除逻辑

在lavaGround和cobbleGround函数开头,先检查并移除旧地形,同时清理ThreeJS资源避免内存泄漏:

function lavaGround() {
  // 移除旧地形
  if (currentGround) {
    scene.remove(currentGround);
    // 销毁几何体和材质,释放内存
    currentGround.geometry.dispose();
    currentGround.material.dispose();
  }

  // 原有的熔岩地形生成逻辑
  const lavaGeometry = new THREE.PlaneGeometry(100, 100);
  const lavaMaterial = new THREE.MeshBasicMaterial({ color: 0xff4500 });
  const lavaPlane = new THREE.Mesh(lavaGeometry, lavaMaterial);
  lavaPlane.rotation.x = -Math.PI / 2;
  lavaPlane.position.y = 0;

  // 将新地形赋值给全局变量
  currentGround = lavaPlane;
  scene.add(currentGround);
}

function cobbleGround() {
  // 同样的移除逻辑
  if (currentGround) {
    scene.remove(currentGround);
    currentGround.geometry.dispose();
    currentGround.material.dispose();
  }

  // 原有的鹅卵石地形生成逻辑
  const cobbleGeometry = new THREE.PlaneGeometry(100, 100);
  const cobbleMaterial = new THREE.MeshBasicMaterial({ color: 0x888888 });
  const cobblePlane = new THREE.Mesh(cobbleGeometry, cobbleMaterial);
  cobblePlane.rotation.x = -Math.PI / 2;
  cobblePlane.position.y = 0;

  currentGround = cobblePlane;
  scene.add(currentGround);
}

3. 按钮绑定逻辑保持不变

你的按钮点击绑定代码不需要修改,因为现在每次点击都会先移除旧地形再生成新的:

document.getElementById('lavaBtn').addEventListener('click', lavaGround);
document.getElementById('cobbleBtn').addEventListener('click', cobbleGround);

额外注意事项

  • 如果你的地形是THREE.Group(包含多个网格对象),同样需要用全局变量保存这个组对象,移除时直接移除组即可,销毁资源时需要遍历组内的每个子对象分别处理。
  • 确保scene变量是全局可访问的,或者通过参数传递到地形生成函数中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:41:18