marqso
marqso

Reputation: 61

A-Frame with aframe-physics-system - address cannon elements from javsascript?

I'm in an A-Frame scene, using its underlying three.js to create objects like:

var boxMaterial = new THREE.MeshPhongMaterial( { map: boxTexture, side: THREE.BackSide, bumpMap: boxBumpMap } );
var boxGeometry = new THREE.BoxBufferGeometry( 20, 20, 20 );
var box01 = new THREE.Mesh(boxGeometry, boxMaterial);
scene.add(box01);

How can I, using javascript, address the underlying Cannon.js of aframe-physics-system to add the StaticBody attribute?

Upvotes: 0

Views: 486

Answers (1)

Piotr Adam Milewski
Piotr Adam Milewski

Reputation: 14655

I'm quite sure you cannot add DOM attributes to js non-DOM objects, such as THREE objects.

The static body attribute is actually creating a new object (CANNON.Body with its type set to Cannon.Body.STATIC). What aframe-physics does is synchronization - the THREE.js mesh with the Cannon.Body.

Source code: body creation here, and syncing here.

You could create a CANNON.Body and synchronize its position with your box, but i would approach it differently:

You can have an empty a-frame entity with the physics attribute:

<a-entity position="0 2 -3" three-setup dynamic-body></a-entity>

but with the material and geometry set in a a-frame component:

AFRAME.registerComponent("three-setup", {
  init: function() {
     var boxMaterial = new THREE.MeshPhongMaterial({
         side: THREE.FrontSide,
     });
     var boxGeometry = new THREE.BoxBufferGeometry(1, 1, 1);
     var box01 = new THREE.Mesh(boxGeometry, boxMaterial);
     this.el.setObject3D('mesh', box01)
  }
})

Check it out in my fiddle

As Don McCurdy pointed out, having a custom a-frame component has more advantages:
- You can listen for the body-loaded event which will notice you when the CANNON.Body is initialized
- it will be accessible with a simple reference: this.el.body


Otherwise, you would need to create a CANNON.Body, and on each render loop apply its position and rotation to your box.

Upvotes: 2

Related Questions