Using cannonjs and Three.js to connect a physics body with a visual mesh

I have written the code below to create two spheres using cannonjs with Three.js for rendering.

var world, mass, body, shape, timeStep=1/60,
    camera, scene, renderer, geometry, material, mesh;
    initThree();
    initCannon();
    animate();

    function initCannon() {
        // Code for initializing Cannon physics
    }

    function initThree() {
        // Code for initializing Three.js graphics
    }

    function animate() {
        // Animation loop
    }

    function updatePhysics() {
        // Update physics
    }

    function render() {
        // Render scene
    }

When I run this code, only the second sphere animates while the first one remains static. The association between the cannonjs body and Three.js mesh seems to be off. I tried adding "body.mesh=mesh", but it didn't solve the issue.

The mesh declaration was originally in initThree(), but I'm unsure if that is causing the problem.

Can someone please help me figure out what I am doing wrong? Let me know if you need more details.

Answer №1

When working with variables, it's important to avoid overwriting them unintentionally. For example, declaring a variable body and then assigning it a new value with body = new CANNON.Body... can lead to the original data being overwritten. To prevent this, consider using distinct variable names like body2 and mesh2 for additional objects.

If you anticipate needing multiple bodies, a more efficient approach is to use Arrays. By storing all bodies in an Array, you can easily iterate through each one individually. For instance:

var bodies = []; // create an array

for (var i = 0; i < 10; i++) {
    bodies.push({ 
        body: new CANNON.Body({mass:0.2}),
        mesh: new THREE.Mesh(geometry, material)
    })
};

Subsequently, you can manipulate each body within the Array using a loop:

for (var i=0, l=bodies.length; i < l; i++) { 
    var body = bodies[i]; 
    // Perform operations on each individual body here
}

This method is more scalable and manageable, allowing you to work with as many bodies as needed without encountering conflicts. In cases where only two bodies are required, simply introducing a separate variable for the second body could provide a quick solution.

Additional resource: https://www.youtube.com/watch?v=tW6pmzd34Hc. This video demonstrates storing circles in an array for clearer understanding.

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

How to Extract Calendar Week Numbers in React from a Specific Month

Is there anyone who can assist me in calculating the week numbers for a specific month? For instance, July is expected to have week numbers 26, 27, 28, 29, and 30. How can I accomplish this task and store the results in an array? Currently, I am only abl ...

Tips for sending information to a child component from a parent in Vue.js

Is there a way to pass the image url to this vue component? I am moving the code to a separate php file that will contain the <script> tag used by Vue, but it seems like it won't recognize the passed data from a parent component. Vue.component( ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...

Implementing jQuery form validation including checking for the strength of the password

My understanding of jQuery was quite basic until I began working on jQuery form validation with password strength check. I successfully completed the password strength check portion, but now I am unsure of how to enable the submit button once the condition ...

Retrieve the full directory path that has been chosen in an HTML form

I am facing a similar issue in my web application where I am using PHP, HTML, and JavaScript. What I want is to be able to select a folder and obtain the full path of that folder for backing up data. For example, when a user enters backup.php, they should ...

Can TrackballControls be used to spin an object around?

Can an object be rotated using TrackballControls instead of the camera? Check out this link to learn more. ...

Ways to verify every entered word without having to click a button

My goal is to implement real-time word checking in a textarea using JavaScript/Angular. I want to validate each word as users are typing it out. What is the best approach for achieving this? ...

Accessing Facebook through Login with only a button visible

I need help with checking the user's login status on Facebook. I have implemented the code provided by Facebook, but all I see is the login button. How can I determine if the user is already logged in or not? function testAPI() { console.log(&apo ...

Creating a worldwide directive using AngularJS

I'm currently working on implementing a directive that will manage user interaction with the navigation system on my website. The directive includes an element.click event listener in the link function, which is responsible for toggling the display of ...

Setting up additional requirements in a subfolder within play.js

Seeking assistance with an issue in play.js on Sandbox. Attempting to install a dependency but my package.json is not located in the root folder; it's stored within a folder named frontend. How can I install them when the package.json is inside that f ...

Executing JavaScript functions when a browser tab is closed

When a user closes the browser tab, I want to call a specific JavaScript function. However, I only want this to occur when the user is actually closing the browser, not during page refreshes, link navigation, form submissions, or pressing the back button. ...

Having trouble importing a React component from a different directory?

I have included the folder structure for reference. Is there a way to successfully import the image component into the card component? No matter which path I try, I keep encountering this error: ./src/Components/Card/Card.js Module not found: Can't ...

The dynamic drop-down menu is giving incorrect values when the onchange function is called

Trying to implement Google Analytics tracking on my dynamic dropdown menu in WordPress has been a bit tricky. I want to be able to track when users click on any of the options and display the name of the selected value, not just the ID. However, I've ...

Setting up the InMemoryCache in Vue ApolloConfiguring the InMemoryCache

I've set up vue-apollo following the instructions in the apollo.config.js file from this guide: (I'm using VSCode). Now, I want to configure the InMemoryCache to exclude the typeName (addTypename: false) like it's explained here: https://w ...

What is the reason for innerHTML not functioning properly when trying to include HTML?

Apologies for my poor English, but I am determined to solve this issue using HTML code. <body> <div id="booklist"> <?php include("../templates/nav.php"); ?> <div class="hero"> <?php include("../templates/aside.ph ...

What is the best way to create a reusable component for a dialog box or modal window?

I have been working on developing a reusable dialog component with a yes or no button at the bottom. The main idea behind this is to create a user confirmation dialog that prompts the user to confirm their entered information before proceeding. import Re ...

Why does my Javascript cross-domain web request keep failing with a Status=0 error code?

UPDATE: I've been informed that this method doesn't work because craigslist doesn't have an Allow-Cross-Domain header set. Fair point. Is there an alternative way to download a page cross-domain using Javascript in Firefox? It's worth ...

What is the process of configuring a custom domain for localhost:3000 in a React application?

"scripts": { "start": "cross-env NODE_PATH=src react-scripts start", "build": "cross-env NODE_PATH=src react-scripts build", } Is there a way to replace localhost:3000 with a custom domain in Rea ...

The Angular ternary operator can be used in conjunction with functions for optimal

Consider this scenario: I have two functions that are triggered by a button click: <button ng-click="functionOne || functionTwo()"></button> However, I want to optimize this setup so that the functions are only called if they return a value. ...

Using jq and node.js to translate AWS EC2 tags

Seeking assistance with transforming this array of EC2 tags using jq and node.js: [ { Key: 'Name', Value: 'xxx' }, { Key: 'role', Value: 'yyy' } ] I want to transform it to: { name : 'xxx', ro ...