Three.js项目中如何在startAnimationLoop中获取独立文件内的Cube?
解决Three.js中动画函数无法访问外部文件创建的Mesh问题
这个问题的核心是JavaScript的参数传递机制——你当前的Mesh函数里,cube = new THREE.Mesh(...)只是在函数内部重新给局部变量赋值,并没有修改外部的this.cube,两者之间的引用关系已经断开了,所以动画函数里自然无法操作到实际的Cube。
下面是两种简单直接的解决方案:
方案一:让Mesh模块返回创建好的Cube
这是最直观的方式,修改你的Mesh.js,让它返回实例化后的Cube,然后在组件中把返回值赋值给this.cube:
修改Mesh.js:
import * as THREE from "three"; export default ({ scene }) => { const geometry = new THREE.BoxGeometry(2, 2, 2); const material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, side: THREE.DoubleSide, flatShading: true, wireframe: false }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); return cube; // 返回创建好的Cube实例 }
然后更新组件的componentDidMount方法,注意调整启动动画的顺序(先创建Cube再启动动画,避免初始帧报错):
componentDidMount() { this.sceneSetup(); // 接收Mesh模块返回的Cube并赋值给this.cube this.cube = Mesh({ scene: this.scene }); Lightss({ scene: this.scene, light: this.lightning }); // 现在cube已存在,再启动动画循环 this.startAnimationLoop(); window.addEventListener("resize", this.handleWindowResize); }
方案二:通过引用对象传递(适合需要传递多个引用的场景)
如果你的场景需要传递多个对象引用,可以用一个空对象作为“容器”,Mesh函数修改这个容器的属性,外部就能获取到创建好的Cube:
修改Mesh.js:
import * as THREE from "three"; export default ({ scene, cubeRef }) => { const geometry = new THREE.BoxGeometry(2, 2, 2); const material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, side: THREE.DoubleSide, flatShading: true, wireframe: false }); // 修改传入的引用对象的属性,外部会同步获取到这个值 cubeRef.cube = new THREE.Mesh(geometry, material); scene.add(cubeRef.cube); }
更新组件的componentDidMount方法:
componentDidMount() { this.sceneSetup(); // 创建一个空对象作为引用容器 const cubeRef = {}; Mesh({ scene: this.scene, cubeRef }); // 从容器中取出Cube赋值给this.cube this.cube = cubeRef.cube; Lightss({ scene: this.scene, light: this.lightning }); this.startAnimationLoop(); window.addEventListener("resize", this.handleWindowResize); }
两种方案都能让你的startAnimationLoop函数正确访问到Cube实例,实现旋转效果。
内容的提问来源于stack exchange,提问作者Arasto
相关产品推荐
相关产品推荐

