這是我嘗試構建的第一個外部JavaScript「模塊」。我使用Babylon.js來創建一個空間場景,我並沒有對庫本身造成麻煩,這與我對使用模塊不太瞭解的東西有關,我想要做的是將構造函數放在另一個文件中。這個構造函數會創建這個我設計的星形網格,如果我把構造函數保存在文件中,它會起作用,如果我把它放在另一個名爲Star.js的文件中,那麼把它放在頭文件的腳本標記中,頁面負荷白色空白。爲babylon.js場景創建模塊
我也試過它環繞在我讀過有關匿名函數的各種圖案括號......似乎並不重要,而且我認爲這應該反正工作。
這是文件中的內容...(解開)
var Star = function (position) {
this.sphere = BABYLON.Mesh.CreateSphere("sphere1", 50, 100, scene);
this.mat = new BABYLON.StandardMaterial("white", scene);
this.mat.diffuseTexture = new BABYLON.Texture("textures/suntexture.jpg", scene);
this.mat.specularColor = new BABYLON.Color3(0, 0, 0);
this.sphere.material = this.mat;
this.sphere.position = position;
this.particleSystem = new BABYLON.ParticleSystem("particles", 15000, scene);
this.particleSystem.particleTexture = new BABYLON.Texture("textures/fireflare.jpg", scene);
this.particleSystem.emitter = this.sphere;
this.particleSystem.color1 = new BABYLON.Color4(0.984, 0.337, 0.047, 1);
this.particleSystem.color2 = new BABYLON.Color4(0.984, 0.757, 0.047, 1);
this.particleSystem.minSize = 8;
this.particleSystem.maxSize = 30;
this.particleSystem.minLifeTime = 0.5;
this.particleSystem.maxLifeTime = 0.8;
this.particleSystem.emitRate = 15000;
this.particleSystem.direction1 = new BABYLON.Vector3(-120, -120, -120);
this.particleSystem.direction2 = new BABYLON.Vector3(120, 120, 120);
this.particleSystem.minAngularSpeed = 0;
this.particleSystem.maxAngularSpeed = Math.PI;
this.particleSystem.minEmitPower = 1;
this.particleSystem.maxEmitPower = 3;
this.particleSystem.updateSpeed = 0.01;
this.particleSystem.start();
};
這裏是什麼樣的文件看起來像(相關部分)
<head>
<script src="js/babylon.js" ></script>
<script src="js/star.js" ></script>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script>
var star1 = new Star(new BABYLON.Vector3(500, 500, 1000));
var star2 = new Star(new BABYLON.Vector3(0, -100, 200));
var star3 = new Star(new BABYLON.Vector3(-600, 200, 1200));
</script>
我讀過很多關於JS模塊修剪的版本...但就像你可以搜索和閱讀,搜索和嘗試要找到答案,當你試圖自己構建它時會有所不同,因爲有那麼一條你沒有的信息。我將以不同的文件夾的方式將整個場景設計爲我的第一個主要項目,所以我的理解在這裏是非常重要的 Thx
Thanks!所以從我的理解來看,它是一個範圍問題。在另一個文件中,場景需要作爲參數傳入,或者沒有「上下文」。看起來我可以把場景放到全球範圍內,它也可以工作。 (我猜是首選封裝) – gson78
是。全局變量通常不是最好的想法,因爲它們可能會導致衝突 – geekonaut