1
votes

I am very new to three.js and javascript so I am not entirely sure whether this is a three.js or javascript issue, but I am unable to inherit from the THREE.Mesh class in the right way and have my mesh displayed on the screen. For some reason I am not allowed to call the constructor new THREE.Mesh( geometry, material ); inside the constructor of my class. Can someone point me in the right direction please.

I read this post: Extending Three.js classes

and got it to work but I would like to use an actual class instead of this strange construct that is proposed there.

    class Icon extends THREE.Mesh{
      constructor(iconName, worldPosition, cameraPosition){
        super();
        this.iconName = iconName;
        this.worldPosition = worldPosition;
        this.cameraPosition = cameraPosition;
        var geometry = new THREE.BoxBufferGeometry( 1, 1, 1 );
        var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );     
        var mesh = new THREE.Mesh( geometry, material );   
        console.log(this.mesh); // Error: undefined
      }
    };
...

scene.add(obj.mesh);
// Error: THREE.Object3D.add: object not an instance of THREE.Object3D.



1
Why would you want to create a new THREE.Mesh(…) inside the constructor for an instance that already is a mesh (through inheritance)? It looks like you either don't want inheritance at all, favouring composition and having the .mesh as a property of your Icon object, or that you should be calling super( geometry, material ); - Bergi
Thank you pointing that out! class Icon extends THREE.Mesh{ constructor(iconName, worldPosition, cameraPosition, colour){ var geometry = new THREE.BoxBufferGeometry( 1, 1, 1 ); var material = new THREE.MeshBasicMaterial( { color: colour } ); let mesh = super(geometry, material ); scene.add(mesh); } - frankBang

1 Answers

2
votes

The correct class would look like so:

class Icon extends THREE.Mesh{
  constructor(iconName, worldPosition, cameraPosition){
    super();
    this.iconName = iconName;
    this.worldPosition = worldPosition;
    this.cameraPosition = cameraPosition;
    this.geometry = new THREE.BoxBufferGeometry();
    this.material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );     
    console.log(this);
  }
};

Instead of creating a new instance of Mesh, the idea is to just assign the new geometry and material to the existing properties geometry and material.