Error in Cannon JS: Position Vector NaN occurs when initializing a body with certain properties

While working with Cannon.js and following online examples, I encountered an issue where setting certain properties in the constructor resulted in NaN values for the position and angular velocity (x, y, z).

For instance, when initializing a body without setting the mass, it does not move:

const body = new CANNON.Body();
console.log(body.position.x, body.mass); //logs 0, 0

However, when specifying the mass in the constructor, the position values become NaN:

const body = new CANNON.Body({
    mass: 1,
});
console.log(body.position.x, body.mass); //logs NaN, 1

Even setting the mass after instantiating the body does not solve the issue.

Here is some additional code context (including the update function called in an animation loop):

export const init = () => {
world = new CANNON.World();
world.gravity.set(0,1,0);
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 10;

for (let i = 0; i < BODIES_COUNT; i++) {
    const shape = new CANNON.Box(new CANNON.Vec3(4,4,4));
    const body = new CANNON.Body({
        mass: 1,
    });
    body.addShape(shape);
    body.position.set(0, 0, 0);
    body.mass = 1;
    body.angularVelocity.set(0, 2, 0);
    body.velocity.set(0, 1, 0);
    body.angularDamping = 0.5;

    world.addBody(body);
    bodies.push(body);

    const geometry = new THREE.BoxGeometry(10, 10, 10);
    const material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
    const mesh = new THREE.Mesh(geometry, material);
    meshes.push(mesh);
}
}

export const update = (delta) => {
    world.step(TIMESTEP * delta);
}

Answer №1

One potential issue to consider is the possibility of inadvertently passing delta = 0 to the world.step function. An example showcasing this issue using Cannon.js v0.6.2 can be found here: JSFiddle

To address this, it is recommended to update your code as follows:

export const update = (delta) => {
    if (delta > 0) {
        world.step(TIMESTEP * delta);
    }
}

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

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

What is the method for condensing content using a Bootstrap toggle button (checkbox)?

Incorporating Bootstrap 5.1, I have a set of buttons that trigger the display or hide some content using the collapse plugin <div class="col m-2"> <button type="btn" class="btn btn-outline-primary m-1" d ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Importing JS files or SDKs in Angular that are not modules

Currently, I am incorporating the Avaya SDK (which consists of 3 JS files) into my Angular project. However, when attempting to import it, I encounter an error stating that it is not recognized as a module. Any suggestions on how to resolve this issue? Th ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

Error encountered in jQuery's addClass and removeClass functions: Unable to read the property 'length' of an undefined value

Upon loading my page, I aim to have some of the div elements hidden initially and display only one. Here is a script that accomplishes this goal: <script> $(document).ready(function () { $(".total").click(function () { $("#pi ...

How to dynamically update the maximum y-axis value in Vue-Chart.js without having to completely re-render the entire

Currently, I am involved in a project that requires the implementation of various charts from the Vue-Chartjs library. One specific requirement is to dynamically change the maximum value on the Y-axis whenever users apply different filters. To achieve this ...

When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application ...

Steps for retrieving the group names of properties in Autodesk Forge

Can someone please help me figure out how to obtain the property group names in Autodesk Forge? I have attempted to use getProperties() and getBulkProperties(), but have had no success in retrieving the group names. Any guidance on how to accomplish this w ...

Restart the JavaScript timer by clicking a button

I am facing an issue with my asp.net page where the session timeout warning keeps appearing even if users are inputting data intermittently. Our company policy has a session timeout warning set in the Master page: var sessionTimeoutWarning = 45; session ...

Best practices for effectively managing errors within JSON web tokens

I am a novice attempting to manage JWT verification. Within the function below, my goal is for the system to generate a new access token based on the refresh token if the user's access token has expired. import { asyncHandler } from "../utils/asy ...

Having trouble showing the text on the screen, but after checking my console, I notice empty divs with p tags. Surprisingly, the app is still functioning properly without any

Currently, I am developing a joke app entirely on my own without any tutorials. One of the components in the app is SportsJokesApi, which retrieves data from a local json folder (SportsJokesData) that I have created. Here is how it is structured: const Sp ...

The deployment of the Fire-base Cloud Function was successful and error-free. However, the function does not appear to exist in the Firebase system

After deploying a JavaScript Cloud Function, it shows that the deployment is completed. However, when I check Firebase, the function is not there. Oddly, TypeScript Cloud Functions deploy successfully. I followed all the steps outlined in the original Fir ...

Eliminate apostrophes in a string by using regular expressions

Can someone help me with this word What is The Answer? I need to eliminate the space and apostrophe '. To remove spaces, should I use this method: data.text.replace(/ +/g, ""). But how can I remove the apostrophe? ...

In Node.js, while running unit tests, the importing function is limited to read-only access

Having trouble mocking an async function in Jest? I followed the documentation and used mockResolvedValue, but encountered a read-only issue when trying to import my mock function from another file. Check out my code below: //index.js async function get ...

Encountering the error "Unable to access the 'pickAlgorithm' property of null" in a ReactJS context

Encountering an issue during npm install process. npm install -g netlify-cli The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a2a5b0a5a2b5fcb2bdb8b4bfa591e1ffe5ffe6"> ...

Difficulty Loading Static JavaScript File in Express.js

Currently in the process of setting up an express server with create-react-app. Encountering this error in the console: Uncaught SyntaxError: Unexpected token < bundle.js:1 Upon clicking the error, it directs me to the homepage htm ...

Tips for capturing the interaction between a jQuery Dialog and its Parent

Within the parent HTML, there is a call that triggers a JavaScript function. <div class="data"> <form:input title="Building" styleClass="content contractorDisable" maxlength="5" size="6" path="fireImpairForm.bldCode" />&nbsp; <a hre ...

A common occurrence is for jQuery/Javascript Ajax POST to generate 6 identical posts when used within a .each loop, happening approximately 20

Context: Building a jQuery mobile phonegap application with multipage-ajaxload and sisyphus enabled form that utilizes an AJAX POST loop to interact with a GUI database. The process involves posting 171 section entries, along with one summary entry to a se ...