0

I am learning three.js and would like to understand how to animate a mesh created by a function outside the regular init().

I'm able to create a cube inside init() and rotate it inside animate(), but if the cube is created by a function outside init() the console says that cube is not defined.

Here's a quick example : http://jsfiddle.net/mattsparrer/yqbp5hx4/10/

function createCube(size) {
    var geometry = new THREE.CubeGeometry(size, size, size);
    var material = new THREE.MeshNormalMaterial();

    cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
    }

By searching on the web I understand "cube" is not in the scope of animate(), but I can't find the proper way to do it. Please can someone explain the way to go ?

Matt Sparrer
  • 189
  • 1
  • 10
  • I've changed a bit the [fiddle](http://jsfiddle.net/prisoner849/uotj19g5/) – prisoner849 Jun 05 '18 at 13:23
  • Thanks for your help @prisoner849 I was looking for something like bind() or creating a loop like the example from Yakudoo, but in fact it was a bit obvious to create the cube before animate it... – Matt Sparrer Jun 05 '18 at 13:43

1 Answers1

0

This isn't so much a Three.js question, but more of a JavaScript variable scope question.

If you declare the cube variable within the init() function, it will only be available inside init(), but not inside render(). You have to declare it outside both these functions for it to be available to both.

Wrong:

function init(){
    // Declaring cube inside this function limits its scope
    var cube = new THREE.Mesh();
}

function render(){
    // Cube is not defined.
    // it's only available within the init() function.
    cube.rotation.y += 0.01;
}

console.log(cube); // Cube is also not defined out here.

Correct:

// Declare cube in global scope so both functions can "see" this variable
var cube;

function init(){
    // Assigns value to existing cube var
    cube = new THREE.Mesh();
}

function render(){
    // cube is also available inside this function
    cube.rotation.y += 0.01;
}

console.log(cube); // No error, because cube exists out here too

For more examples about variable scope, see here: What is the scope of variables in JavaScript?

M -
  • 26,908
  • 11
  • 49
  • 81
  • Thanks @Marquizzo I tried it before posting, my mistake was to believe that the place of animate() in the script wasn't important – Matt Sparrer Jun 05 '18 at 16:36
  • Ah, order of operations is also very important. If you call `animate` before calling `createCube` then there won't be any cube to animate! It should be 1: `init();` 2:`createCube(150);` and 3: `animate();` – M - Jun 05 '18 at 16:58