Search code examples
javascriptthree.jsaframe

Why does not render? / Aframe with three object3D


I want to use threejs with aframe. threejs object does not rendered.

How can I render three object in aframe?

html

<a-scene>
  <a-entity geometry material id="obje"></a-entity>
  <a-entity camera id="cam"></a-entity>
</a-scene>

js

window.addEventListener('load', init);

function init() {
  width = document.body.clientWidth;
  height = document.body.clientHeight;

  camera = new THREE.PerspectiveCamera(100, width / height);
  camera.position.set(0, 0, +1000);

  const geometry = new THREE.BoxGeometry(400, 400, 400);
  const material = new THREE.MeshNormalMaterial();
  box = new THREE.Mesh(geometry, material);

  const entityEl = document.querySelector('#obje');
  entityEl.setObject3D('mesh', box);

  const cam = document.querySelector('#cam');
  cam.setObject3D('camera', camera);
};

Solution

  • Two main issues:

    1. The presented THREE.js code is redundant. The camera component already initializes a THREE.PerspectiveCamera and geometry and material set a mesh on the entity with a geometry and a material. See glitch illustrating
    2. If the built-in components don't provide the functionality you need, you don't have to use them and I recommend encapsulating your code in a component. Glitch illustrating