【问题标题】:three.js action on click(requestAnimationFrame)三.js点击动作(requestAnimationFrame)
【发布时间】:2026-01-18 08:45:01
【问题描述】:

我希望在单击按钮时相机不断旋转 + = 事实证明,有一个触发器持续 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();

【问题讨论】:

  • 你能澄清第一段吗?尤其是“当按钮被点击时+=,结果是有一个触发2秒(点击时)并结束”。你到底想要什么?
  • 我想要一个参数,例如 x,在单击时进入 requestanimationframe,并且不仅仅是 5,而是 + = 5

标签: javascript three.js requestanimationframe


【解决方案1】:

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

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

animate 内部,我们检查是否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)
});

【讨论】: