I'm new to THREE.js coming from an AS3/Away3D background. I'm trying to create a custom object class that extends THREE.Object3D to add to my scene. CustomObject will encapsulate a lot of behavioural properties and methods. Ideally I'd like to pass each CustomObject it's own data object which will determine how it will look/move/behave. Encapsulating this code will keep my main.js a lot cleaner.
My problem is I can't seem to add an instance of the class directly to my scene. I can only add the mesh via the CustomObject.getMesh() method. Is it possible to add an instance of the class directly to my scene to render? Here's a very basic attempt I've put together from what I've been able to find online and in the /src:
function CustomObject(){
THREE.Object3D.call( this );
this.type = 'CustomObject';
this.geometry = new THREE.BoxGeometry( 540, 540, 14 );
this.mesh = new THREE.Mesh( this.geometry, new THREE.MeshLambertMaterial( { color: 0xff0000 } ) );
}
CustomObject.prototype = Object.create( THREE.Object3D.prototype );
CustomObject.prototype.constructor = THREE.Object3D;
CustomObject.prototype.getMesh = function(){
return this.mesh;
}
I'd like to be able to add the CustomObject class directly to the scene to make object management a lot cleaner. Can anyone tell me how this is achievable please?
Many thanks in advance!
David
If you want to add your custom object to the scene directly, you can use a pattern like this one:
function CustomObject() {
this.type = 'CustomObject';
this.geometry = new THREE.BoxGeometry( 540, 540, 14 );
this.material = new THREE.MeshLambertMaterial( { color: 0xff0000 } );
THREE.Mesh.call( this, this.geometry, this.material );
}
CustomObject.prototype = Object.create( THREE.Mesh.prototype );
CustomObject.prototype.constructor = CustomObject;
CustomObject.prototype.getMesh = function() {
return this.mesh;
}
var foo = new CustomObject();
scene.add( foo );
three.js r.71
来源:https://stackoverflow.com/questions/31923047/creating-custom-object3d-class