Turn off body collisions in Cannon.js

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

Answer №1

If you want to exclude a CANNON.Body from the simulation, simply execute the following code:

world.removeBody(groundBody);

In order to add it back into the simulation, all you need to do is run:

world.addBody(groundBody);

Removing and adding the body like this is completely acceptable. This approach can actually improve the performance when running word.step().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access undefined properties (attempting to read 'getBoundingClientRect')

I keep encountering the issue TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect') while working in React on my localhost with Node.js. I can't figure out what's causing it. import React,{useRef,useState} fro ...

Guide on passing a shortened object to the view in Express.js

Hey there, I'm new to programming and currently working on setting up a basic blog using Express.js and Mongoose. In my code snippet below, I have successfully written a function that displays 6 articles from my database (each article has a simple Art ...

Obtaining Data from an XML Node Using AJAX

Trying to extract statistics from my XML based on a specific name request, but encountering issues with my JavaScript functionality. XML data: <player> <forward><name>Joe</name><stats>45</stats></forward> <f ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

Having trouble accurately obtaining the height of a DIV element using jQuery

After trying to troubleshoot on my own, I ran into a roadblock due to my specific requirements not being met by existing solutions. The issue at hand is as follows: I have a sticky DIV element positioned to the left, nested within another DIV Element wit ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Is it possible to replace JavaScript files that are included in my index page if I am utilizing conditional comments specifically for IE9?

My website works perfectly in all browsers, except for IE9. After some investigation, I discovered that the issue lies with a jQuery plugin called multilevelpush.js. While it works great on other browsers, it simply won't cooperate with IE9. Upon fur ...

Using State.go in JavaScript involves waiting for it to finish before proceeding

After implementing a JS code snippet as shown below: exports.openTab = function(location) { var $state = app.getInjector().get( '$state' ); var opts = {}; var toParams = {}; toParams.id = "myPage"; $state.g ...

The Vuex state keeps acting mysterious by claiming to be undefined

Here is my post.js located in src > store > post.js: import Vuex from 'vuex' import Vue from 'vue' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { testState: 'Hello&apo ...

Using either AngularJS's simple .then method or the $q service to handle asynchronous requests

I'm trying to understand the distinction between AngularJS $q service and simply using .then() after an asynchronous request. For example, using .then(): function InboxService($http) { this.getEmails = function getEmails() { return $http.get(& ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

Steer clear of excessive stretching when using Three.js

I am working on wrapping a 3D model with textures in three js. However, I have noticed that in certain areas of the model, the image appears to be stretching even though the texture resolution is high. https://i.sstatic.net/9hcoA.png ...

Utilizing Three.js: Incorporating shadows onto a see-through surface

I'm attempting to modify the lighting of a MeshPhongMaterial: https://i.sstatic.net/F4eZM.png I want to make the visible part transparent while still preserving the shadows. Using a ShadowMaterial removes the radial lighting effect, leaving only obj ...

Storing data as a JSON string in a JavaScript object and saving it to

Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly. This issue arose after deploying the website on Vercel. Storing "cart" as ...

The checkboxes do not appear to be updating visually when the "checked" property is toggled programmatically

Check out this example on JSFiddle for a demonstration. Clicking on a checkbox should cause all the neighboring checkboxes to toggle on or off. Even though the "checked" property is toggling, there doesn't seem to be any visual change. n.prop("chec ...

Radio button onchange event not triggering

I have a group of radio buttons that are supposed to trigger the hider(something); function when they change, whether they are checked or unchecked. The script works correctly when the radio buttons are checked and call the JS function. However, if a diffe ...

Invoke a Java script function for Regular Expression validation failure in ASP.NET

I have a <asp:RegularExpressionValidator> that validates a text box, and I also have a JavaScript function that prevents entering non-numerical values in the textbox. When I use the expression validator alone, it works fine. However, as soon as I add ...

Combining multiple meteor servers into a single database collection (local)

I'm currently working on a Meteor project that involves making multiple external API calls at different intervals and storing the retrieved data in MongoDB. My goal is to separate these API calls into individual "micro-services", each running on its ...

The position of the scroll bar remains consistent as you navigate between different websites

Is it possible for me to click on a link within my HTML website and have the other website load with me in the exact same position? For example, if I'm halfway down a webpage and click a link, can I be taken to that same point on the new page? If so, ...

What is the best starting dataset to use from a large pool of data points when creating a stock line chart in High

I am working on creating a line stock highchart similar to the example shown here: https://www.highcharts.com/demo/stock/lazy-loading In the provided example, the initial load fetches data from https://demo-live-data.highcharts.com/aapl-historical.json, s ...