I've searched everywhere and looked well issues and doc, but it seem that appart from creating a constraint between two Cannon bodies, there is no way to group shapes of different masses (for example).

For the moment I use lockConstraint but that's a hack...and sometimes, when my object is colliding, the rotation of the ""child"" object rotate suddently in unwanted position...

Is there a more proper way to do so ?

Edit: What I am trying to achieve is: I have created a vehicle, I want his center of mass to be at the center of the 4 wheels.For this I create a body with .collisionResponse set to 0 and the mass I want and position it at center of wheels.Then I create the chassis with a very little mass and new CANNON.LockConstraint(chassisBody, mass, 0.5) that allow the 2 objects to be "grouped".

1

Best Answer


There is no way to set mass/density per Shape in Cannon.js. However, you can move the center of mass closer to the heavier shape to get an equivalent effect.

A hammer is a good example, because the density of the head is much larger than the shaft in a typical hammer. If you throw a hammer, it will rotate around a point close to its head because the head is heavier than the shaft.

To make a hammer in cannon.js, you could use 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));

Now, to assemble the shapes into one Body, you do something like this:

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

Depending on the shape positions you use (shaftPosition, headPosition) you can change their position locally in the Body, and at the same time, their positions relative to the center of mass (aka center of rotation).Setting headPosition=(0,0,0) and shaftPosition=(0,3,0) would make the hammer spin around the head when throwing the hammer. However if you put it the other way around, the hammer would spin around the center of the shaft... which would look like the head and shaft have similar density. Experiment with different positions to find your perfect center of rotation relative to the shapes.

The full signature of Body#addShape lets you add a full rigid transform to position the shapes within the body. It is:

body.addShape(shape, position, quaternion);