Items plummeting below the surface plane within cannon.js and three.js

I've recently delved into the world of physics engines, specifically utilizing cannon-es.js alongside three.js.

However, I've encountered a challenge where the box and loaded model are simply passing through the plane and disappearing from view. I attempted to rectify this by employing

groundBody.quaternion.setFromEuler(-Math.PI/2,0,0)
, but the objects ended up moving upwards on the screen instead of downwards. It seems like there might be some issues with positioning and dimensions. Could someone please offer me some guidance on this matter? Your assistance would be greatly appreciated!

Here is the code snippet I'm currently working on:

<html>
  <head>
    <title>My 3D Model</title>
    <script type="module">
        // import statements for various libraries and modules
      // code for setting up the renderer, scene, camera, lights, physics world, and loading models
      // animation function for updating the scene based on physics calculations
      // event listener for window resize
</script>
</head>
<body>
</body>
</html>

Answer №1

finally

If you're looking for a quick solution, consider using negative rotation for the groundbody: groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0), and set the position for your boxbody as boxBody.position.y = 100.

However, whether this is the correct approach or why it works over other methods is still uncertain.

Below are some alternative solutions.


Although I'm not well-versed in cannonJS, it appears that there are two working options. For instance, in https://github.com/schteppe/cannon.js?files=1, where gravity is set to the Z coordinate, simply adjust the gravity to the Z coordinate and omit the rotation with the plane. Then, assign a position to boxBody.position.z = 100 and observe the results.

Alternatively, you can resize your plane geometry by using the new CANNON.Plane() shape, or a new CANNON.Box(new CANNON.Vec3(15, 15, 1)) shape where the Z coordinate is only 1 (this becomes the Y size after rotation). In this scenario, set the position in Y instead of Z (boxBody.position.y = 100). The issue in the provided example, in my opinion, is that both physics are combined in each, leading to a failure.

Below are some code snippets that should function correctly:

  const groundBody = new CANNON.Body({
    shape: new CANNON.Box(new CANNON.Vec3(15, 15, 1)),
    type: CANNON.Body.STATIC,
  });

  world.addBody(boxBody);
  boxBody.position.y = 100;

Additional note: Since your plane is static, there's no need to constantly update its position in the animation loop. I have tested this with an example from and it works smoothly.

const planeGeometry = new THREE.PlaneGeometry(25, 25);
const planeMesh = new THREE.Mesh(
    planeGeometry,
    new THREE.MeshPhysicalMaterial({ color: "white" })
);
planeMesh.rotateX(-Math.PI / 2);
planeMesh.receiveShadow = true;
scene.add(planeMesh);
const planeShape = new CANNON.Plane();
const planeBody = new CANNON.Body({ mass: 0 });
planeBody.addShape(planeShape);
planeBody.quaternion.setFromAxisAngle(
    new CANNON.Vec3(1, 0, 0),
    -Math.PI / 2
  );
  world.addBody(planeBody);

It's important to set the initial position of your boxBody to avoid it being in the ground plane at the start, as this could result in excessive velocity for the boxBody.


Alternatively, based on your code template:

  1. Set boxBody.position.y = 100
  2. Avoid rotating your groundBody
  3. Rotate your groundMesh as desired: groundMesh.rotateX(-Math.PI / 2);
  4. Apply the rotation to your groundBody: groundBody.quaternion.copy(groundMesh.quaternion).

The issue might not be straightforward; it could be challenging to rotate the cannon body. Instead, consider adding the mesh's quaternion after rotation. Remember not to perform a world step update until the objects have the correct initial positions. Therefore, groundBody.quaternion.copy(groundMesh.quaternion) should precede the world.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

TypeScript will show an error message if it attempts to return a value and instead throws an

Here is the function in question: public getObject(obj:IObjectsCommonJSON): ObjectsCommon { const id = obj.id; this.objectCollector.forEach( object => { if(object.getID() === id){ return object; } }); throw new Erro ...

Tips for continuing code execution in an ajax success function following the completion of a nested ajax call within the success block

I am facing an issue with a function that utilizes $.ajax. In the success section of the function, I have three nested functions. The first one executes properly, but the second one contains another $.ajax call. While the internal $.ajax call works fine, t ...

Loading your NextJS page with a full-page loader

I am looking to create a full-page loader for my NextJS app, similar to this example: https://jsfiddle.net/yaz9x42g/8/. The idea is that once the content is loaded, it should be revealed in a visually appealing way. I want to build a reusable component tha ...

An error occurred while attempting to save a new entry using the New Entry Form in DataTable, stating that the variable "

I have encountered an issue with a table that includes a bootstrap modal containing a form. After filling out the form and saving the data or closing the modal, I want to refresh the table data. However, I am receiving the following error: TypeError: c i ...

Tips for finding group words within a div panel

Check out this interactive demo I created to demonstrate what I need help with. There are multiple panels containing words, each separated by a line break. I am trying to create a filter that will hide panels that do not match the words entered in the sea ...

Steps for selectively extracting objects from an array containing nested objectsNeed a way to isolate specific objects

Currently, I am working on a project in JavaScript and have created an array called folders that holds multiple objects: folders = [folder1, folder2, folder3...] Each object within the array has various properties, one of which is docs that is an array o ...

Leveraging highland.js for sequentially executing asynchronous functions while maintaining references to the initial stream data

I am dealing with a series of events: var eventStream = _([{ id: 1, foo: 'bar' }, { id: 2, foo: 'baz' }]); My task is to load an instance of a model for each event in the stream (my Data Access Layer returns promises) and then tri ...

The hunt is on for greater value within the index

My requirement is to check the text content of a box. If it matches any value stored in an ARRAY, then I have to execute a specific action. var ARRAY1 = ["Saab", "Volvo", "BMW"]; if (select[i].innerHTML.indexOf('ARRAY1') != -1){//code here} ...

Best practices for utilizing Async/Await in Node 8: A comprehensive guide

With node version 8, async/await becomes available, making code linear for the first time in nodejs natively. This is a nice improvement. In the past, many articles claimed that functions with try/catch blocks were not optimized in the v8 javascript engi ...

Finding the IP address from a hostname in Node.js: A step-by-step guide

I am looking for a solution to resolve a hostname defined in the hosts file to its corresponding IP address. Take, for instance, my hosts file located at "/etc/hosts": 127.0.0.1 ggns2dss81 localhost.localdomain localhost ::1 localhost6.localdomain ...

Tips for deploying an Angular application with Node.js

Currently, I've set up a nodejs backend by following a tutorial to integrate tweets into the frontend of my application. As I prepare to deploy to a development server, I have successfully built the frontend using ng build --prod. However, I am facin ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

JavaScript never forgets to validate the user input

Forgive me for my lack of experience, but I am new to this and seeking guidance. I am struggling to find a straightforward example on how to validate HTML input using JavaScript. Currently, I am working on a search function and need help in implementing ...

What is the most effective way to exchange data among multiple React applications?

I am looking for a solution to securely share data among multiple applications, with some parts of the data being secure and others not. I have explored options like IndexedDB and localStorage, but they don't work in all browsers, especially in incogn ...

How can I change the color of a designated column in a Google stacked bar chart by clicking a button?

I am in the process of creating a website that compares incoming students at my university across different academic years. We have successfully implemented a pie chart to display data for the selected year. Now, we aim to include a stacked bar chart next ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Issue: The 'loopback' module is not found in the NodeJS environment

I can't seem to solve the issue I'm experiencing. Error: Module 'loopback' not found These are the dependencies listed in my package.json file: "loopback": "^3.19.0", "loopback-boot": "^2.6.5", "loopback-component-explorer": "^6.0. ...

What could be causing the Firebase email verification to result in a 400 error?

I've been struggling to implement email verification in my React website. Every time I try to use the sendSignInLinkToEmail function, I keep encountering this error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=XXXXXXXXXXX ...

How can I resolve the Vue warning about an unknown custom element <password-input>?

I've been working on resolving an error within a component, but unfortunately, I'm still encountering issues. The error message is as follows: [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive co ...

Creating experiences for websites controlled by gestures

It's been a great experience working on a website that utilizes gesture-based technology. My inspiration for this project came from various sources, including this link. Despite researching extensively through websites, Google, Wikipedia, and GitHub, ...