Extending Three.js classes

懵懂的女人 提交于 2021-02-07 14:26:26

问题


I want to extend the Three.js Object3D class, but can't figure out how to do it.

There's this Stackoverflow question, which I've read, re-read and tried, but can't get it to work for me.

Is there a way to extend a ThreeJS object?

Could anyone offer some specific code on how to get this going? Here's what I have at the moment:

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

And to create an instance:

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

But calling the "add" method of the MyObject3D instance returns an error that "thing" has no method "add."

What's the deal?


回答1:


You're setting the prototype to CubeGeometry, which has no add method. Based on the way you're trying to instantiate the object, it looks like you actually want your object to have the Mesh prototype.

Most likely you want something like this:

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;

Then to instantiate it:

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


来源:https://stackoverflow.com/questions/18043171/extending-three-js-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!