1

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.



2
  • 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 ); Commented Sep 27, 2020 at 3:32
  • 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); } Commented Sep 27, 2020 at 6:31

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.