1

我在 javascript 中具有三个函数parsinginitanimate. Parsing必须首先调用,因为没有它,positions数组不会被修改,这是函数init需要的。奇怪的是, animate 需要由controls创建的变量,init但它们曾经被同时调用,并且以前可以工作。我已经尝试了调用函数的所有可能组合,但要么controls是未定义的,要么positions是。这是我的代码的最后一次迭代。

var positions = [];
parsing();

function parsing() {
    fetch('Petit_film_256_atomes.txt').then(response => response.text()).then(text => {
        const arr = text.split('\n')
            .map(line => line.trim())
            .map((arr) => arr.split(' '))
            .map(([size, x, y, z]) => ({ 
                  size: Number(size), 
                  x: Number(x), 
                  y: Number(y), 
                  z: Number(z) 
            }));
            while (arr.length > 0) {
                positions.push(arr.splice(0, size).slice(2));
            }
        init();
        animate();
    })
}
...
function init() {
    renderer = new THREE.WebGLRenderer({antialias:true});
    renderer.setSize(WIDTH, HEIGHT);
    document.body.appendChild(renderer.domElement);
    ...
    console.log(positions);
    for (var i = 0; i < 256; i++) {
        atom = sphere.clone();
        atom.position.set( positions[0][i].x, positions[0][i].y, positions[0][i].z );
        scene.add( atom );
        group.push( atom );
    }
    ...
    controls = new THREE.OrbitControls(camera, renderer.domElement);    
}

function animate() {
     requestAnimationFrame(animate);
     renderer.render(scene, camera);
     controls.update();
}

此外,console.log(positions)显示了一个非空数组,但显示的错误仍然positions是未定义的。有人知道为什么吗?

4

0 回答 0