我在Angular项目中使用三.js。我想加载一个简单的.obj文件并将其移动到画布上。代码工作正常;但是,我必须在我的animate()-函数中显式执行空检查,以查看模型是否已加载。如果不进行空值检查,控制台将记录以下内容:类型错误:无法在 TestComponent.animate 上读取 null 的属性“位置”(test.component.ts:71)我想这是因为实例引用尚未设置,因为此时 OBJLoader 仍在忙于加载资源。最小可验证示例:import * as THREE from 'three';import { OBJLoader2 } from 'three/examples/jsm/loaders/OBJLoader2.js';import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';import { MtlObjBridge } from 'three/examples/jsm/loaders/obj2/bridge/MtlObjBridge.js';@Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'],})export class TestComponent implements AfterViewInit { @ViewChild('rendererContainer') rendererContainer: ElementRef; renderer: THREE.WebGLRenderer; scene = null; camera = null; mesh = null; loader = null; female = null; constructor() {} ngAfterViewInit() { this.init(); this.animate(); } init() { this.renderer = new THREE.WebGLRenderer(); this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.setSize(window.innerWidth, window.innerHeight); this.rendererContainer.nativeElement.appendChild(this.renderer.domElement); this.scene = new THREE.Scene(); this.scene.add(new THREE.AmbientLight(0xffffff)); this.camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 ); this.camera.position.z = 500; this.loader = new OBJLoader2(); new MTLLoader().load('./../../assets/models/female02.mtl', (mtl) => { this.loader.setModelName('female02'); this.loader.setLogging(true, true); this.loader.addMaterials( MtlObjBridge.addMaterialsFromMtlLoader(mtl), true ); this.loader.load( './../../assets/models/female02.obj', (object3d) => { this.female = object3d; this.scene.add(object3d); }, null, null, null ); }); }有没有更好的方法来操作动画循环中的对象,而不必每次都执行空检查?
2 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
如果需要在加载任何内容之前触发动画循环,另一种方法是将引用替换为虚拟对象:
const nullObject= new Object3D()
let female = nullObject
let male = nullObject
let child = nullObject
//...
function onLoad( trueObject ) {
female = trueObject
}
这样,您可以期望存在所有方法和成员,但它们将是noops。
添加回答
举报
0/150
提交
取消