【问题标题】:Extending Three.js classes扩展 Three.js 类
【发布时间】:2013-08-05 08:08:16
【问题描述】:

我想扩展 Three.js Object3D 类,但不知道怎么做。

有这个 Stackoverflow 问题,我已经阅读、重新阅读并尝试过,但无法让它为我工作。

Is there a way to extend a ThreeJS object?

谁能提供一些具体的代码来说明如何实现这一点?这是我目前拥有的:

var MyObject3D = function() {
   THREE.Object3D.call(this);
   MyObject3D.prototype = new THREE.CubeGeometry();
   MyObject3D.prototype.constructor = MyObject3D;
}

并创建一个实例:

var thing = new MyObject3D();
var testGeo = new THREE.CubeGeometry(10, 10, 10);
var testMat = new THREE.MeshPhongMaterial();
var testMesh = new THREE.Mesh(testGeo, testMat);
thing.add(testMesh);

但是调用 MyObject3D 实例的“add”方法会返回“thing”没有“add”方法的错误。

怎么了?

【问题讨论】:

    标签: javascript three.js


    【解决方案1】:

    您将原型设置为 CubeGeometry,它没有添加方法。根据您尝试实例化对象的方式,看起来您实际上希望您的对象具有网格原型。

    你很可能想要这样的东西:

    var MyObject3D = function() {
        // Run the Mesh constructor with the given arguments
        THREE.Mesh.apply(this, arguments);
    };
    // Make MyObject3D have the same methods as Mesh
    MyObject3D.prototype = Object.create(THREE.Mesh.prototype);
    // Make sure the right constructor gets called
    MyObject3D.prototype.constructor = MyObject3D;
    

    然后实例化它:

    var testGeo = new THREE.CubeGeometry(20, 20, 20);
    var testMat = new Three.MeshNormalMaterial();
    var thing = new MyObject3D(testGeo, testMat);
    

    【讨论】:

    • 谢谢!!当我创建问题时,CubeGeometry 只是一个复制/粘贴错误,但你仍然解决了我的问题 :) 我在构造函数中设置了新类的原型。把它移到外面固定它。我很好奇为什么这会有所作为。 (您可能已经注意到我仍在学习 Javascript 中的 OO。)
    • 原型在构造函数运行之前被应用到对象实例,因此当您在构造函数中设置 MyObject3D.prototype 时,这不会对使用该构造函数实例化的第一个对象生效。但是,在构造函数运行一次之后,原型会发生变化,因此该类型的所有未来对象都将具有看起来像您想要的样子的原型。 (尽管它们都会略有不同,因为您要为每个对象实例化一个新对象!)
    • 我其实有点理解,很奇怪。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2017-04-20
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多