这可能是一个three.js的问题,但我认为它更可能是我仍然不能正确理解原型继承。这里是我的代码 - 有点简单:JavaScript继承三,js
define(["jquery", "three", "svgUtils", "views/walls", "floor", "scene", "furniture"], function ($, THREE, SvgUtils, Walls, Floor, scene, Furniture) {
function Section (svgNode) {
if (!(this instanceof Section)){
throw new TypeError("Constructor cannot be called as a function");
}
this.svgNode = svgNode;
this.name = svgNode.id.replace("section-", "");
if (this.name == "first") {
this.position.y = 100;
}
}
Section.prototype = new THREE.Object3D();
Section.prototype.constructor = Section;
return Section;
});
这是一个require.js模块,我定义截面这是一个Object3D。然后,我使用new Section(svgNode)
创建了两个部分 - 但尽管其中只有一个名称为“first”,但他们的y位置都设置为100.为什么?
UPDATE
感谢HMR现在我敢肯定,这是一个继承的问题。下面是我如何创建包含墙壁和地板XML数据的建筑物的部分(即楼层):
define(["jquery", "three", "svgUtils", "views/walls", "floor", "scene", "furniture"], function ($, THREE, SvgUtils, Walls, Floor, scene, Furniture) {
function Section (svgNode) {
if (!(this instanceof Section)){
throw new TypeError("Constructor cannot be called as a function");
}
THREE.Object3D.call(this);
this.svgNode = svgNode;
this.name = svgNode.id.replace("section-", "");
this.wallsNode = $(svgNode).find('[id*="walls"]');
if (this.wallsNode.length == 0) {
throw new Error("Section missing walls node")
}
this.walls = new Walls(this.wallsNode);
this.add(this.walls);
this.add(new Floor($(svgNode).find('[id*="floor"]')));
if (this.name == "first") {
this.position.y = 100;
}
}
Section.prototype = Object.create(THREE.Object3D.prototype);
Section.prototype.constructor = Section;
return Section;
});
如果我创建了一楼,把它添加到场景是这样的:
sections[0] = new section(sectionsXml[0]); scene.add(sections[0]);
我将底层添加到现场 - 这正是我期望的。
但是如果我同时创建一楼和二楼,但添加只一楼,像这样:
sections[0] = new section(sectionsXml[0]); sections[1] = new section(sectionsXml[1]); scene.add(sections[0]);
一楼包含了一楼的墙壁以及(道歉美国 - 在这里我们称地面楼层为'第一'层 - 这是欧洲的事情)。
这就像是当我调用部分[0]的构造函数时,我不知道这是怎么回事。
,伟大的 - 和一个真正的好文章。使用call(this)将Object3D的所有属性添加到我的Section中。然而,继承问题现在已经成为三个问题。我有两个部分占据相同的空间,所以我正在移动一个在另一个之上。我可以看到,我已经在第一个对象上方的第二个对象100上设置了y位置 - 当我检查两个对象时,我可以看到第一个对象的位置为(0,0,0),第二个对象(0,100,0)的位置。然而,这两个对象现在都移动到(0,100,0)。为什么? – wagster 2015-02-12 22:51:50
@wagster确保你使用Object.create来设置继承的原型部分 – HMR 2015-02-13 11:33:28
感谢HMR。花了很长时间才弄明白这一点。事实证明,问题不在该科出现,而是在墙内。墙也使用新的而不是Object.create()。一旦我更新了Walls,所有事情都开始按照原样进行。 – wagster 2015-02-20 23:12:00