为babylon.js场景创建模块

Creating a module for babylon.js scene

本文关键字:创建 模块 babylon js      更新时间:2023-09-26

这是我尝试构建的第一个外部JavaScript"模块"。我"我使用Babylon.js来创建一个空间场景。我对库本身没有问题。这与我不了解使用模块有关。我想做的是在另一个文件中放入一个构造函数。这个构造函数的实例将创建我设计的这个星形网格。如果我将构造函数保存在文件中,它就可以工作。如果我把它放在另一份名为star.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

这不是模块化的问题,而是scene变量的错误。

我猜scene是脚本文件中的一个变量,这就是为什么只要Star构造函数位于同一文件中,它就可以了。

构造函数定义了一个参数(position),但没有定义scene

一旦您也将scene传递到构造函数中,它就可以工作了。

请参阅此处的工作代码示例