创建自定义 Object3D 类

2024-03-03

我是来自 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 类直接添加到场景中,以使对象管理更加清晰。谁能告诉我这是如何实现的?

提前谢谢了!

David


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

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 );

三.js r.71

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建自定义 Object3D 类 的相关文章

随机推荐