1

I have a wrapper entity with child entities with meshes:

<a-entity id="parent" dynamic-body="shape: none">
  <a-entity id="box" geometry="primitive: box" position="1 2 3"></a-entity>
  <a-entity geometry="primitive: sphere" position="3 4 5"></a-entity>
</a-entity>

I am adding the shapes with three-to-cannon and CANNON. For example with a box.

parentEl = document.querySelector('#parent');
childEl = parentEl.querySelector('#box');
parentEl.body.addShape(
    mesh2shape(childEl.getObject3D('mesh'), {type: mesh2shape.Type.BOX}),
    new CANNON.Vec3().copy(childEl.object3D.position),
    new CANNON.Quaternion().copy(childEl.object3D.quaternion));

Since the children are offset, but the dynamic-body/shape are being added to the parent, does the above code look right to apply that? I currently have code to grab and throw objects, but the objects act very erratically (goes too fast, rolls weirdly on the ground, shakes around in the hand)

1 Answer 1

1

I got this working by changing the center of mass (e.g., the position of the parent entity) to the average positions of the children:

  // Move center of mass, currently just the average of the positions of the shapes.
  centerOfMass = new THREE.Vector3();
  for (i = 0; i < shapeEls.length; i++) {
    centerOfMass.add(shapeEls[i].object3D.position);
  }
  centerOfMass.divideScalar(shapeEls.length);
  body.position.copy(centerOfMass);
  this.el.setAttribute('position', body.position);

And then apply the center of mass to the offsets of the shapes, and also sync to A-Frame:

     for (i = 0; i < shapeEls.length; i++) {
       shapeEl = shapeEls[i];
       shapeOffset = new CANNON.Vec3().copy(shapeEl.object3D.position).vsub(centerOfMass);
        body.addShape(
         this.getShape(shapeEl.getObject3D('mesh'), shapeEl.getAttribute('data-shape')),
           shapeOffset,
           new CANNON.Quaternion().copy(shapeEl.object3D.quaternion));
      shapeEl.setAttribute('position', shapeOffset);
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.