Combining A-frame with Three.js

Fabian Tjoe A On picture Fabian Tjoe A On · Jun 29, 2016 · Viewed 8.6k times · Source

I was wondering...

Is it possible to add Three.js elements to a A-frame scene? Assuming A-frame is built upon Three.js, and

three Version: ^0.74.0

is logged into your console it shouldn't be a weird thing right?

I tried this code onto my A-frame scene element:

let scene = document.getElementsByTagName('a-scene');
console.log(scene);

var sphereMaterial = new THREE.MeshLambertMaterial( {  } );
var sphere = new THREE.Mesh( new THREE.SphereGeometry( 15, 10, 10 ), sphereMaterial );
    sphere.position.set(150, 20, -170);
    scene.add( sphere );

But it doesnt work because the scene object doesnt have a add function.. Maybe because the A-frame scene is not an instance of a normal WebGLRenderer?

Does anybody have experience with this? It would be very awesome!

Answer

ngokevin picture ngokevin · Jul 13, 2016

A-Frame is built on top of three.js and exposes all underlying functionality.

<a-scene>.object3D gives you access to the THREE.Scene.

Each <a-entity> has an object3D that is a group. You use getObject3D(name) and getOrCreateObject3D(name, constructor to add things to the group.

To add three.js elements within the A-Frame framework, use the Entity-Component system that A-Frame provides.

AFRAME.registerComponent('mythreejsthing', {
  schema: {
    // ... Define schema to pass properties from DOM to this component
  },

  init: function () {
    var el = this.el;  // Entity.
    var mythreejsobject = // ... Create three.js object.
    el.setObject3D('mesh', mythreejsobject);
  }
});

https://aframe.io/docs/0.2.0/core/entity.html#object3d https://aframe.io/docs/0.2.0/core/component.html