What is the method for organizing object bodies (parent/child) in Cannon.js?

After extensively searching and reviewing issues and documentation, it seems that apart from establishing a constraint between two Cannon bodies, there is no direct method to unite shapes of varying masses.

Currently, I am using the lockConstraint approach, but I consider it to be a temporary solution. Occasionally, when my object collides, the rotation of the "child" object abruptly shifts to an unintended position...

Is there a more appropriate way to accomplish this?

Edit: My goal is to create a vehicle with the center of mass aligned with the center of the 4 wheels. To achieve this, I have set up a body with .collisionResponse set to 0 and the desired mass, positioning it at the center of the wheels. Subsequently, I establish the chassis with minimal mass and a new

CANNON.LockConstraint(chassisBody, mass, 0.5)
to effectively link the two objects together.

Answer №1

In Cannon.js, it is not possible to set mass/density per Shape directly. However, a workaround is to adjust the center of mass to achieve a similar effect.

Consider the example of a hammer, where the head is denser than the shaft. When a hammer is thrown, it rotates around a point close to its head due to the weight distribution.

To create a hammer in cannon.js, you can utilize two boxes:

var head = new CANNON.Box(new CANNON.Vec3(2,1,1));
var shaft = new CANNON.Box(new CANNON.Vec3(0.5,3,0.5));

To combine these shapes into a single Body, you can do the following:

var body = new CANNON.Body({ mass: 1 });
body.addShape(shaft, shaftPosition);
body.addShape(head, headPosition);

By adjusting the shape positions (shaftPosition, headPosition), you can control their position within the Body and the center of mass, affecting the rotation behavior.

Experiment with different positions to find the optimal center of rotation for your shapes. The full signature of Body#addShape allows adding a transform to position the shapes:

body.addShape(shape, position, quaternion);

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

Trigger file download with ajax and php

I have been using an image picker plugin to select an image and then force it to download. Initially, I hard coded the PHP which worked perfectly fine. The download pop-up appeared and I was able to view the file without any issues. However, when trying to ...

Error Found in Angular2 Console Inspection

So, when I check the webpage inspection console, I see this error: Uncaught SyntaxError: Unexpected token { at Object.<anonymous> (main.bundle.js:3885) at __webpack_require__ (polyfills.bundle.js:51) at eval (eval at <anonymous> (m ...

Which is better: specifying Node.js version with nvmrc or in package.json engines

Ensuring that other developers working on my JavaScript project use specific versions of node and npm is important to me. I recently added the following code snippet to my package.json file: "engineStrict" : true, "engines": { "node" : "10.10.0", ...

Even after being removed, the input field in Firefox stubbornly maintains a red border

I have a project in progress that requires users to input data on a modal view and save it. The validation process highlights any errors with the following CSS snippet: .erroreEvidenziato { border: 1px solid red; } Here is the HTML code for the moda ...

Error 404: "Headers already sent to the client cannot be modified"

I'm currently developing a Node/Express application and I want it to display a 404 page if a promise function doesn't resolve. This is my approach: app.get("/projects", t("projects", function(req, res) { res.header("Cache-Control", "private ...

Mobile compatibility in ECMAScript 5.1 is essential for creating seamless user

Is there a reliable source for information on ECMAScript 5.1 compatibility with mobile browser devices? ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

How can we bring in prop array values in React?

I've been working on developing a small music player program in React. Is there a way to import all these values together with a single import statement? I noticed that manually inputting the values into the props array doesn't work because the ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

How can I insert a button into a Flatlist using React Native?

Is there a way to add a single scrollable button inside a FlatList without duplicating it? I've been experiencing issues where adding a button inside the FlatList results in multiple buttons being displayed. On the other hand, placing the button outs ...

Attempting to grasp the correct method for understanding For loops

Lately, I've been diving into teaching myself Node.JS and it has been quite an enjoyable experience. However, I've hit a frustrating roadblock that is really causing me some grief. For some reason, I just can't seem to grasp the concept of F ...

Dynamically loading iframes with JQuery

I have implemented a jQuery script to load another URL after a successful AJAX request. $(document).ready(function() { var $loaded = $("#siteloader").data('loaded'); if($loaded == false){ $("#siteloader").load(function (){ ...

Is it possible for a React blog to be included in search engine results?

As I work on building my blog using React, Node.js, Express, Sequelize, and other technologies, a question has arisen in my mind: Will search engines index my articles, or will only the homepage of my site be noticed? For instance, if I have an article ti ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...

Encountering an error when utilizing the ForEach method

Encountering a problem with using forEach: I am receiving an error message stating "unhandledRejection: TypeError: data.forEach is not a function" Here is the solution I attempted: I converted the data into JSON format before using forEach const data = JS ...

Navigating to a different URL in a remoteMethod with Loopback and Express

Can anyone provide any guidance on how to redirect to a URL within a model function or remoteMethod? I've been struggling to find documentation on this. Here is the code snippet for reference: Model Function (Exposes /catch endpoint) Form.catch = func ...

Tips for maintaining the original ng-click initialized value as the ng-init value after the page is refreshed

My ng-repeat feature includes buttons for liking and disliking images. The problem I'm facing is that each time the page refreshes, the count of likes and dislikes gets reset to the initial value set by ng-init. How can I maintain the incremented lik ...

Switching between multiple images using Jquery on a click event

Hi there, I am currently working on a project where I need to use jQuery to switch between three images when clicked. Once the third image is clicked, it should cycle back to the first picture. I was wondering if there is a way to modify the code below so ...

I am looking to transform CSV data into XLSX file format, upload it to AWS, and obtain the corresponding URL

I am currently in the process of converting a JSON file to CSV. My next step is to convert this CSV file to XLSX data and upload it to AWS to retrieve the link. Convert CSV to XLSX const xlsxFilePath = 'path/to/transaction_data.xlsx'; await csvto ...