创建自定义Object3D类

时间:2015-08-10 15:06:32

标签: javascript class three.js extend

我是来自AS3 / Away3D背景的THREE.js的新手。我正在尝试创建一个自定义对象类,它扩展了THREE.Object3D以添加到我的场景中。 CustomObject将封装许多行为属性和方法。理想情况下,我想传递每个CustomObject它自己的数据对象,这将决定它的外观/移动/行为。封装此代码将使我的main.js更清洁。

我的问题是我似乎无法将类的实例直接添加到我的场景中。我只能通过CustomObject.getMesh()方法添加网格。是否可以直接将类的实例添加到我的场景中进行渲染?这是我从网上和/ 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;

}

我希望能够将CustomObject类直接添加到场景中,以使对象管理更加清晰。有人能告诉我这是如何实现的吗?

非常感谢提前!

大卫

1 个答案:

答案 0 :(得分:7)

如果要直接将自定义对象添加到场景中,可以使用如下图案:

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