扩展 Three.js 类 [英] Extending Three.js classes

查看:30
本文介绍了扩展 Three.js 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展 Three.js Object3D 类,但不知道如何去做.

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

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

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

有没有办法扩展 ThreeJS 对象?

谁能提供一些关于如何实现这一目标的具体代码?这是我目前所拥有的:

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

并创建一个实例:

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".

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

这是怎么回事?

推荐答案

您将原型设置为 CubeGeometry,它没有 add 方法.根据您尝试实例化对象的方式,您似乎确实希望对象具有 Mesh 原型.

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;

然后实例化它:

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

这篇关于扩展 Three.js 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆