我想每隔x秒将地球仪旋转到某个位置。但是,如果我尝试使用setTimeout将render()放入for循环中,它将一口气运行整个过程,而不是每次都执行。
我想这与render()的递归性有关,但是我想知道以前是否有人遇到过这个问题以及如何解决这个问题?
谢谢!
var lat=41.9028;
var long=12.4964;
var requestId = 0;
var targetx=lat * ( Math.PI / 180 );
var targety=(270 - long ) * ( Math.PI / 180 );
//i would like to repeat this periodically every x seconds
render(targetx,targety);
function render(tx,ty) {
controls.update();
sphere.rotation.x += (targetx - sphere.rotation.x) * 0.1;
sphere.rotation.y += (targety - sphere.rotation.y) * 0.1;
clouds.rotation.x += (targetx - clouds.rotation.x) * 0.1;
clouds.rotation.y += (targety - clouds.rotation.y) * 0.1;
var verticalOffset = 0.1;
renderer.render(scene, camera);
camera.lookAt( scene.position );
requestAnimationFrame(function(tx,ty){render(tx,ty)});
}
答案 0 :(得分:0)
您在上面的代码示例中使用的requestAnimationFrame
错误。如果您想要60FPS动画,则无需将render()
包装到另一个函数中,因为这可能会导致无限递归问题。只需执行此操作,您就会自动获得每秒60帧的渲染调用:
requestAnimationFrame(render);
您也不需要将tx, ty
参数传递给render()
,因为它们没有被使用。
如果您只想每秒更新一次,那么您正在寻找的是window.setInterval()
:
// i would like to repeat this periodically every 1 seconds
// Second argument is the delay in millisecs
window.setInterval(render, 1000);
function render() {
controls.update();
sphere.rotation.x += (targetx - sphere.rotation.x) * 0.1;
sphere.rotation.y += (targety - sphere.rotation.y) * 0.1;
clouds.rotation.x += (targetx - clouds.rotation.x) * 0.1;
clouds.rotation.y += (targety - clouds.rotation.y) * 0.1;
var verticalOffset = 0.1;
renderer.render(scene, camera);
camera.lookAt( scene.position );
// You don't need requestAnimationFrame, since you're not doing 60FPS
// requestAnimationFrame(render);
}
// This updates target rotations
changeTarget() {
targetx = Math.random() * Math.PI;
targety = Math.random() * Math.PI;
}
See here,获取有关window.setInterval
工作方式的文档。