[SOLVED] Uncaught Error: Trying to add an element that doesn't have an `object3D`

Hello. I’m trying to build an A-Frame component to apply displacement maps on glTF models.

I’m stuck with this Uncaught Error: Trying to add an element that doesn’t have an object3D.

Here’s my code:

AFRAME.registerComponent('user-displacement-map', {

	schema: {
	},

	init: function () {

		this.el.addEventListener('object3dset', this.applyDisplacementMap.bind(this));

	},

	applyDisplacementMap: function() {

		var scene = this.el.sceneEl;

		var mesh = this.el.getObject3D('mesh');

		mesh.traverse(function(meshNode) {

			var dispTextureLoader = new THREE.TextureLoader();

			dispTextureLoader.load(

				// TODO Get texture URL from user data.
				'textures/grey_roof_tiles_Disp_4k.jpg',

				function(displacementTexture) {

					if ( meshNode.material && 'displacementMap' in meshNode.material ) {

						meshNode.material.displacementMap = displacementTexture;
						meshNode.material.needsUpdate = true;

						if ( meshNode.geometry && 'attributes' in meshNode.geometry && 'uv' in meshNode.geometry.attributes ) {

							/**
							 * @see https://threejs.org/examples/webgl_materials_displacementmap.html
							 */

							var displacementGeometry = meshNode.geometry;
							displacementGeometry.attributes.uv2 = displacementGeometry.attributes.uv;
							displacementGeometry.center();

							displacementMesh = new THREE.Mesh(displacementGeometry, meshNode.material);
							displacementMesh.scale.multiplyScalar(25);

							// FIXME "Uncaught Error: Trying to add an element that doesn't have an `object3D`"
							scene.add(displacementMesh);

						}

					}

				}

			);

		});

	}

});

Please help me.

You will have better luck with A-Frame questions on Stack Overflow with the aframe tag, or in the A-Frame Slack channel.

But in any case, you cannot add a THREE.Mesh object to an HTML element like <a-scene/>. Try meshNode.add(displacementMesh) or scene.object3D.add(displacementMesh) instead. Probably the latter, so you’re not adding to the object while you traverse it. I find it helpful to use variable names like meshEl or sceneEl to refer to HTML elements, so they are not confused with the three.js objects they represent.

1 Like

var scene = this.el.sceneEl.object3D; instead of var scene = this.el.sceneEl; removes the error.

Thanks a lot!

Samuel, thanks a lot