這可能是一個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