[英]How to animate a mesh created outside init() in three.js?
I am learning three.js and would like to understand how to animate a mesh created by a function outside the regular init(). 我正在学习three.js,并且想了解如何为常规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. 我可以在init()内部创建一个多维数据集,并在animate()内部旋转它,但是如果该多维数据集是由init()外部的函数创建的,则控制台会说未定义多维数据集。
Here's a quick example : http://jsfiddle.net/mattsparrer/yqbp5hx4/10/ 这是一个简单的示例: 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. 通过在Web上搜索,我了解“多维数据集”不在animate()的范围内,但是我找不到正确的方法。 Please can someone explain the way to go ?
请有人可以解释走的路吗?
This isn't so much a Three.js question, but more of a JavaScript variable scope question. 这不是一个Three.js问题,而是一个JavaScript 变量范围问题。
If you declare the cube
variable within the init()
function, it will only be available inside init()
, but not inside render()
. 如果申报
cube
的内部变量init()
函数,它将只提供内部init()
而不是内部的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? 有关变量范围的更多示例,请参见此处: JavaScript中变量的范围是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.