Search code examples
javascriptfunctionparametersthree.js3d

animation with tree.js does not accept my torus


I am new to Three.js and cannot work out why this animation does not accept the torus as a parameter. Without setting 'torusToBeMoved' as a parameter it works just perfectly fine..

const geometry = new THREE.TorusGeometry(25, 0.2, 26, 100);
const material = new THREE.MeshStandardMaterial({ color: 0xccaa55 });
const torus = new THREE.Mesh(geometry, material);
torus.position.set(-15, -15, -15);

scene.add(torus);

function animate(torusToBeMoved) {
  requestAnimationFrame(animate(torusToBeMoved));

  torusToBeMoved.rotation.x += 0.01;
  torusToBeMoved.rotation.y += 0.005;
  torusToBeMoved.rotation.z += 0.01;
  controls.update();

  renderer.render(scene, camera);
}

animate(torus);```

Solution

  • You are running into a "Maximum call stack size exceeded" error since you are passing the return value of the function as parameter instead of passing the function as parameter. Utilizing a callback as parameter should solve the issue:

    const animate = (torusToBeMoved) => {
      torusToBeMoved.rotation.x += 0.01;
      torusToBeMoved.rotation.y += 0.005;
      torusToBeMoved.rotation.z += 0.01;
    
      controls.update();
      renderer.render(scene, camera);
    
      requestAnimationFrame(() => animate(torusToBeMoved));
    }