Plantera
Plantera

Reputation: 36

Disable collision of body in Cannon.js

I have a bunch of planes that fit together to form terrain. Each individual plane has it's own cannon.js body (I use three.js for rendering visuals) for collision. Due to memory constraints I de-render each object when the player moves to far away from the object. I can de-render objects easily in three.js just by turning them invisible, but there's no clear way to do this in cannon.js. Basically I want to disable a cannon.js object without deleting it outright.

I've already looked through the docs and there's basically nothing on how to do this. I've also seen no questions on any form on this topic.

Example code below to show you how I want to implement this.

//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();

Upvotes: 0

Views: 2257

Answers (1)

schteppe
schteppe

Reputation: 2084

To exclude a CANNON.Body from the simulation, run the following:

world.removeBody(groundBody);

To add it back again, run:

world.addBody(groundBody);

It’s perfectly fine to remove and add it back like this. It will help you get better performance when running word.step().

Upvotes: 3

Related Questions