I have a collection of planes that come together to create a terrain. Each plane has its own physics body using cannon.js
(I utilize three.js
for rendering). To conserve memory, I hide objects when the player moves too far away from them in the game world. While it's easy to hide objects in three.js
, there isn't a straightforward way to do this in cannon.js
. Essentially, I am looking to disable a cannon.js
object without completely removing it.
I've scoured the documentation but haven't found any information on how to achieve this. Additionally, I haven't come across any discussions or questions related to this topic online.
Below is an example code snippet demonstrating how I'd like to implement this functionality:
// Generating terrain
for (let z = 0; z < 6; z++) {
for (let x = 0; x < 6; x++) {
// Creating cannon.js hitbox
const groundShape = new CANNON.Box(new CANNON.Vec3(2,0.125,2));
const 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);
// Creating three.js plane
const 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() {
// Check if player is outside the loading distance of an object
for(let i = 0; i < maparray.length; i++){
if(Math.abs(maparray[i].position.x - player.position.x) < loadDistance && Math.abs(maparray[i].position.z - player.position.z) < loadDistance) {
// Code here should disable collisions for the object.
}
}
}
animate();