创建自定义的Object3D类

3
我是一个新手,之前接触的是AS3/Away3D技术。我正在尝试创建一个自定义对象类,它继承了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

1个回答

9

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

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


谢谢WestLangley! 完美地工作并且非常清晰易懂。 我曾经尝试了另一种方法,但现在它运行得非常好。 干杯! - DTids
你选择了哪个解决方案? - WestLangley
啊,好的,我现在接受了,对此很抱歉。我使用了第一种方法,因为第二种方法给我报了一个错误:“Uncaught TypeError:Cannot read property 'length' of undefined”,我无法解决。这是我之前尝试做的方式。但你提供的第一种方法可以正常工作,所以我现在将坚持使用它。再次感谢您的帮助! - DTids
1
第二个解决方案对我有用,但我不喜欢它,所以我删除了它。 - WestLangley
4
可以使用 ES6 类实现相同的功能吗? - Théo Champion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接