如果我在关注,您想在 ng 2 个组件中保留和重用巴比伦场景对象的状态吗?我只是通过创建一个场景服务组件为我的项目做了类似的事情,该组件被注入到每个需要引用它的类中。
我选择不在服务组件中实际初始化场景(考虑到组件生命周期和我的代码中初始化场景的点)而是在初始化画布时设置场景服务场景。
完成后,组件可以根据需要共享和使用巴比伦场景服务组件:
场景服务.ts
import { Injectable } from '@angular/core';
@Injectable()
export class SceneService {
private _scene:BABYLON.Scene;
get scene(): BABYLON.Scene {
return this._scene;
}
set scene(scene:BABYLON.Scene){
this._scene = scene;
}
}
babylon.component.ts
@Component({
selector: 'app-babylon',
templateUrl: './babylon.component.html',
styleUrls: ['./babylon.component.css']
})
export class BabylonComponent implements OnInit, OnDestroy {
constructor(private babylonEngine:BabylonEngine, private sceneSerice:SceneService, private fileSystem:FileSystem) { }
scene:BABYLON.Scene = null;
ngOnInit(): void {
var canvas = document.getElementById('renderCanvas') as HTMLCanvasElement;
var engine = this.babylonEngine.init(canvas);
// create a basic BJS Scene object
this.scene = new BABYLON.Scene(engine);
this.sceneSerice.scene = this.scene;
}
}
初始化场景的一些用户:
@Component({
selector: 'app-scene-editor',
templateUrl: './scene-editor.component.html',
styleUrls: ['./scene-editor.component.css']
})
export class SceneEditorComponent implements OnInit {
@ViewChild('jscolor') input;
constructor(private sceneService:SceneService, public fileSystem:FileSystem) {
}
ngOnInit():void {
this.meshes = this.sceneService.scene.meshes;
this.materials = this.sceneService.scene.materials;
}
}
app.module.ts
providers: [
SceneService,
FileSystem,
BabylonEngine
],