首页 > 解决方案 > 三.js点击动作(requestAnimationFrame)

问题描述

我希望相机在单击按钮时不断旋转 + = 事实证明,有一个触发器持续 2 秒(单击时)并结束。

let btn = document.querySelector('.btn--left');
btn.addEventListener('click',function(event) {
     camera.position.x+=(3*Math.sin(angle/6));
     camera.position.z+=(3*Math.cos(angle/6));
});

let angle = 0;

const animate = function () {
     requestAnimationFrame( animate );
     angle-=Math.PI/180*2;

     renderer.render( scene, camera );
     controls.update();
     camera.updateProjectionMatrix();
};

animate();

标签: javascriptthree.jsrequestanimationframe

解决方案


如果我理解正确你想要这个:https ://codepen.io/adelriosantiago/pen/QWEpvLg?editors=1010

在此处输入图像描述

基本上,有一个shouldRotate变量指示相机何时应该旋转。默认情况下是false.

在里面animate我们检查 if shouldRotate === true,如果这成立,那么旋转就会发生。

if (shouldRotate) {
  angle -= Math.PI/180*2;
  camera.position.x+=(3*Math.sin(angle/6));
  camera.position.z+=(3*Math.cos(angle/6));
}

单击按钮时,setTimeout设置为 2 秒。当计时器结束时,它会做shouldRotate = false。像这样:

btn.addEventListener('click',function(event) {
  shouldRotate = true;
  setTimeout(() => {
    shouldRotate = false;
  }, 2000)
});

推荐阅读