【问题标题】:Disable collision of body in Cannon.js在 Cannon.js 中禁用身体碰撞
【发布时间】:2019-04-11 01:05:00
【问题描述】:

我有一堆飞机可以组合在一起形成地形。每个单独的飞机都有自己的cannon.js 身体(我使用three.js 来渲染视觉效果)用于碰撞。由于内存限制,当玩家远离对象时,我会取消渲染每个对象。我可以在three.js 中轻松地取消渲染对象,只需将它们设为不可见,但在cannon.js 中没有明确的方法可以做到这一点。基本上我想禁用 cannon.js 对象而不直接删除它。

我已经浏览了文档,基本上没有关于如何执行此操作的内容。我也没有看到有关此主题的任何形式的问题。

下面的示例代码向您展示我想如何实现它。

//terrain generation
for (z=0; z<6; z++) {
 for (x=0; x<6; x++) {

 //cannon.js hitbox creation
 var groundShape = new CANNON.Box(new CANNON.Vec3(2,0.125,2));
 var groundBody = new CANNON.Body({ mass: 0, material: zeromaterial});
 groundBody.addShape(groundShape);
 groundBody.position.set(x*4,0,z*4);
 world.addBody(groundBody);
 maparray.push(groundBody);

 //three.js plane creation
 grassmesh = new THREE.Mesh(grassgeometry, grassmaterial);
 grassmesh.castShadow = true;
 grassmesh.receiveShadow = true;
 grassmesh.position.set(x*4,0,z*4);
 scene.add(grassmesh);
 maparray.push(grassmesh);
 }
}
...
function animate() {
 //detect if player is outside of loadDistance of object
 for(i=0; i<maparray; i++){
  if(Math.abs(maparray[i].position.x - player.position.x) <  
  loadDistance && Math.abs(maparray[i].position.z - 
  player.position.z) < loadDistance) {

   //code here magically turns off collisions for object. 

  }
 }
}
animate();

【问题讨论】:

  • 请展示您到目前为止所做的尝试以及您在代码中遇到问题的地方。
  • 已编辑以包括代码的实现。

标签: javascript three.js cannon.js


【解决方案1】:

要从模拟中排除 CANNON.Body,请运行以下命令:

world.removeBody(groundBody);

要重新添加它,请运行:

world.addBody(groundBody);

像这样删除并重新添加它是完全可以的。它会帮助你在运行 word.step() 时获得更好的性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多