函数调用后对象变为数字 - Javascript

Object Becomes Number After Function Call - Javascript

我正在使用 Three.js 创建动画,但我的 animate() 功能无法正常工作。简化代码如下:

let obj;
let camera = new THREE.PerspectiveCamera(fov, asp, near, far);
let scene = new THREE.Scene();
const loader = new THREE.GLTFLoader();
async function init() {
    obj = await loader.loadAsync("./public/modelo/scene.gltf");
    scene.add(obj.scene);
    animate(obj.scene.children[0]);
    renderer.render(scene, camera);
    function animate(objeto){
        console.log(objeto);
        requestAnimationFrame(animate);
        objeto.rotation.z += 0.005;
        renderer.render(scene, camera);
    }
}
init();

该函数在第一次调用时有效,但之后我可以通过我的 console.log() 语句看到出错的地方。在 animate() 的第一个 运行 上,该行按预期打印出对象。但是,在所有随后的调用中,该语句只是 returns 一个浮点数,随着每次连续调用而大大增加。我检查并确保对象在第一次函数调用结束时完好无损,所以我不确定这里发生了什么。有什么建议吗?

问题出在您代码中的这一行:

requestAnimationFrame(animate);

MDN documentationrequestAnimationFrame,您传递给它的回调 - 这里 animate 是:

The function to call when it's time to update your animation for the next repaint. The callback function is passed one single argument, a DOMHighResTimeStamp similar to the one returned by performance.now(), indicating the point in time when requestAnimationFrame() starts to execute callback functions.

换句话说,您的 animate 被调用时带有时间戳 - 在某些方面我认为它的行为很像数字(我个人并不熟悉 DOMHighResTimeStamp 是什么) ,并解释您所看到的内容。它肯定不会被你的“objeto”作为参数调用。

为确保这一点,只需作为回调函数传入,函数就会使用正确的参数调用 animate。将上面的调用替换为

requestAnimationFrame(() => { animate(objeto); });

编辑:或者正如@Bergi 所建议的,我们可以通过在 init 函数中的 animate 之外简单地定义 objeto 来完全避免需要参数。由于您总是使用相同的参数调用 animate,因此无需专门传递它,因此您的代码可以是:

async function init() {
    obj = await loader.loadAsync("./public/modelo/scene.gltf");
    const objeto = obj.scene.children[0];
    scene.add(obj.scene);
    animate();
    renderer.render(scene, camera);
    function animate(){
        console.log(objeto);
        requestAnimationFrame(animate);
        objeto.rotation.z += 0.005;
        renderer.render(scene, camera);
    }
}