创建自定义Object3D类

DTi*_*ids 2 javascript class extend three.js

我是来自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;

}
Run Code Online (Sandbox Code Playgroud)

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

提前谢谢了!

大卫

Wes*_*ley 8

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

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 );
Run Code Online (Sandbox Code Playgroud)

three.js r.71

  • @WestLangley是否可以使用ES6类实现相同的功能? (3认同)